博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
(C#) Handling and Raising Events
阅读量:5074 次
发布时间:2019-06-12

本文共 8879 字,大约阅读时间需要 29 分钟。

Handling and Raising Events

.NET Framework 4.5
 
Other Versions
 
 
6 out of 20 rated this helpful 
 

 

Events in the .NET Framework are based on the delegate model. The delegate model follows the observer design pattern, which enables a subscriber to register with, and receive notifications from, a provider. An event sender pushes a notification that an event has happened, and an event receiver receives that notification and defines a response to it. This article describes the major components of the delegate model, how to consume events in applications, and how to implement events in your code.

For information about handling events in Windows Store apps, see .


An event is a message sent by an object to signal the occurrence of an action. The action could be caused by user interaction, such as a button click, or it could be raised by some other program logic, such as changing a property’s value. The object that raises the event is called the event sender. The event sender doesn't know which object or method will receive (handle) the events it raises. The event is typically a member of the event sender; for example, the event is a member of the  class, and the  event is a member of the class that implements the interface.

To define an event, you use the event (in C#) or Event (in Visual Basic) keyword in the signature of your event class, and specify the type of delegate for the event. Delegates are described in the next section.

Typically, to raise an event, you add a method that is marked as protected and virtual (in C#) or Protected and Overridable (in Visual Basic). Name this method OnEventName; for example, OnDataReceived. The method should take one parameter that specifies an event data object. You provide this method to enable derived classes to override the logic for raising the event. A derived class should always call the OnEventName method of the base class to ensure that registered delegates receive the event.

The following example shows how to declare an event named ThresholdReached. The event is associated with the  delegate and raised in a method named OnThresholdReached.

C#
 
class Counter{    public event EventHandler ThresholdReached;    protected virtual void OnThresholdReached(EventArgs e)    {        EventHandler handler = ThresholdReached;        if (handler != null)        {            handler(this, e);        }    }    // provide remaining implementation for the class}

A delegate is a type that holds a reference to a method. A delegate is declared with a signature that shows the return type and parameters for the methods it references, and can hold references only to methods that match its signature. A delegate is thus equivalent to a type-safe function pointer or a callback. A delegate declaration is sufficient to define a delegate class.

Delegates have many uses in the .NET Framework. In the context of events, a delegate is an intermediary (or pointer-like mechanism) between the event source and the code that handles the event. You associate a delegate with an event by including the delegate type in the event declaration, as shown in the example in the previous section. For more information about delegates, see the  class.

The .NET Framework provides the  and  delegates to support most event scenarios. Use the delegate for all events that do not include event data. Use the  delegate for events that include data about the event. These delegates have no return type value and take two parameters (an object for the source of the event and an object for event data).

Delegates are multicast, which means that they can hold references to more than one event-handling method. For details, see the  reference page. Delegates provide flexibility and fine-grained control in event handling. A delegate acts as an event dispatcher for the class that raises the event by maintaining a list of registered event handlers for the event.

For scenarios where the  and  delegates do not work, you can define a delegate. Scenarios that require you to define a delegate are very rare, such as when you must work with code that does not recognize generics. You mark a delegate with the delegate in (C#) and Delegate (in Visual Basic) keyword in the declaration. The following example shows how to declare a delegate namedThresholdReachedEventHandler.

C#
 
public delegate void ThresholdReachedEventHandler(ThresholdReachedEventArgs e);

Data that is associated with an event can be provided through an event data class. The .NET Framework provides many event data classes that you can use in your applications. For example, the  class is the event data class for the  event. The .NET Framework follows a naming pattern of ending all event data classes with EventArgs. You determine which event data class is associated with an event by looking at the delegate for the event. For example, the  delegate includes the  class as one of its parameters.

The  class is the base type for all event data classes.  is also the class you use when an event does not have any data associated with it. When you create an event that is only meant to notify other classes that something happened and does not need to pass any data, include the class as the second parameter in the delegate. You can pass the  value when no data is provided. The  delegate includes the class as a parameter.

When you want to create a customized event data class, create a class that derives from , and then provide any members needed to pass data that is related to the event. Typically, you should use the same naming pattern as the .NET Framework and end your event data class name with EventArgs.

The following example shows an event data class named ThresholdReachedEventArgs. It contains properties that are specific to the event being raised.

C#
 
public class ThresholdReachedEventArgs : EventArgs{    public int Threshold { get; set; }    public DateTime TimeReached { get; set; }}

To respond to an event, you define an event handler method in the event receiver. This method must match the signature of the delegate for the event you are handling. In the event handler, you perform the actions that are required when the event is raised, such as collecting user input after the user clicks a button. To receive notifications when the event occurs, your event handler method must subscribe to the event.

The following example shows an event handler method named c_ThresholdReached that matches the signature for the  delegate. The method subscribes to the ThresholdReached event.

C#
 
class Program{    static void Main(string[] args)    {        Counter c = new Counter();        c.ThresholdReached += c_ThresholdReached;        // provide remaining implementation for the class    }    static void c_ThresholdReached(object sender, EventArgs e)    {        Console.WriteLine("The threshold was reached.");    }}

The .NET Framework allows subscribers to register for event notifications either statically or dynamically. Static event handlers are in effect for the entire life of the class whose events they handle. Dynamic event handlers are explicitly activated and deactivated during program execution, usually in response to some conditional program logic. For example, they can be used if event notifications are needed only under certain conditions or if an application provides multiple event handlers and run-time conditions define the appropriate one to use. The example in the previous section shows how to dynamically add an event handler. For more information, see  and .


If your class raises multiple events, the compiler generates one field per event delegate instance. If the number of events is large, the storage cost of one field per delegate may not be acceptable. For those situations, the .NET Framework provides event properties that you can use with another data structure of your choice to store event delegates.

Event properties consist of event declarations accompanied by event accessors. Event accessors are methods that you define to add or remove event delegate instances from the storage data structure. Note that event properties are slower than event fields, because each event delegate must be retrieved before it can be invoked. The trade-off is between memory and speed. If your class defines many events that are infrequently raised, you will want to implement event properties. For more information, see .


 

Title

Description

Contains examples of raising and consuming events.

Shows how to use event properties to handle multiple events.

Describes the design pattern that enables a subscriber to register with, and receive notifications from, a provider.

Shows how to handle an event that is raised by a Web Forms control.


Reference

Other Resources

Did you find this helpful? Yes No
 

转载于:https://www.cnblogs.com/fdyang/p/3203219.html

你可能感兴趣的文章
poj 2186 tarjan求强连通分量(模板题)
查看>>
selenium 关于富文本的处理
查看>>
【bzoj3512】DZY Loves Math IV 杜教筛+记忆化搜索+欧拉函数
查看>>
2019年春季学期第九周作业.
查看>>
利用Heritrix+htmlparser爬网页并进行解析
查看>>
找到自己的行星轨迹
查看>>
CLR via C#(08)-操作符
查看>>
要研究的内容
查看>>
json文件
查看>>
行变列 拼接字符串 MSSQL 一个超级搞的问题
查看>>
mongoDB之C#and.net Driver
查看>>
nginx 日志怎么实现显示真实客户端IP
查看>>
linux下shapely的安装
查看>>
Linux MySQL5.6.36安装手册
查看>>
fdffafadf
查看>>
Mysql常用命令操作之增删改查
查看>>
SharePoint 2010 Ribbon with wrong style in Chrome and Safari
查看>>
Archlinux 踩坑实录
查看>>
路由器 NorFlash与NandFlash区别
查看>>
iptables/Netfilter 学习
查看>>