event in C #

Source: Internet
Author: User

Classes or objects can notify you of events that occur when other classes or objects are concerned. The class that sends (or raises) an event is called the publisher, and the class that receives (or handles) the event is called a Subscriber.

Events Overview

Events have the following characteristics:

L The Publisher determines when an event is raised and the Subscriber determines what action is taken to respond to the event.

L an event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers.

L an event without a subscriber will never be invoked.

L events are typically used to notify user actions, such as button clicks or menu selection actions in the graphical user interface.

L If there are multiple subscribers to an event, when the event is raised, multiple event handlers are used at the same pace.

L can use event synchronization threads.

L in the. NET Framework class Library, events are based on EventHandler delegates and EventArgs base classes.

the implementation principle of the event

An event is a message sent by an object to signal notification of the occurrence of an operation. The action may be caused by user interaction, such as a mouse click, or by some other program logic. The object that raises the event is called the sender of the event. The object that captures the event and responds to it is called the event receiver.

In event communication, the event sender class does not know which object or method will receive (handle) the event it raises. What is needed is a medium (or a mechanism similar to a pointer) between the source and the receiver. The. NET Framework defines a special type (Delegate) that provides functionality for function pointers.

A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class has a signature, and it can only refer to methods that match its signature. In this way, the delegate is equivalent to a type-safe function pointer or a callback. Although delegates have many other uses, only the event-handling capabilities of delegates are discussed here. A delegate declaration is sufficient to define a delegate class. Declares the signature that provides the delegate, and the common language runtime provides the implementation.

Event delegates are multicast, which means that they can refer to multiple event-handling methods. The delegate considers flexibility and precise control in event handling. By maintaining the list of registered event handlers for the event, the delegate acts as the event dispatcher role for the class that raised the event.

Events are special types of multicast delegates that can only be invoked from the class or struct in which they are declared (the Publisher Class). If another class or struct subscribes to the event, its event handler method is invoked when the event is raised by the Publisher class. EventHandler Delegation

The EventHandler delegate represents a method that will handle events that do not contain event data.

[SerializableAttribute]

[ComVisibleAttribute (True)]

public delegate void EventHandler (

Object sender,

EventArgs E

)

Sender: Event source.

E: EventArgs that does not contain any event data.

The standard signature of an event handler delegate defines a method that has no return value, the type of the first argument is Object, it references the instance that raised the event, and the second parameter derives from the EventArgs type, which holds the event data. If the event does not generate event data, the second argument is just an instance of the EventArgs. Otherwise, the second parameter is a custom type derived from EventArgs, providing all the fields or properties required to save the event data.

EventHandler is a predefined delegate that is designed to represent event handler methods for events that do not generate data. If the event generates data, you must provide your own custom event data type, and you must either create a delegate where the type of the second parameter is a custom type, or use a generic EventHandler delegate class to replace the generic type parameter with a custom type.

To associate an event with the method that handles the event, add an instance of the delegate to the event. Unless the delegate is removed, the event handler is invoked whenever the event occurs. EventArgs base class

EventArgs is the base class for the class that contains the event data.

This class does not contain event data, which is used by events that do not pass state information to an event handler when the event is raised. If the event handler requires state information, the application must derive a class from this class to hold the data.

For example, the System.assemblyloadeventargs class is used to hold data for assembly load events and contains System.Reflection.Assembly that describe the assemblies that are loaded.

Subscribe to Events Programmatically

Defines an event handler method whose signature matches the delegate signature of the event. For example, if an event is based on a EventHandler delegate type, the following code represents a method stub:

void Handlecustomevent (object sender, CustomEventArgs e)

{

Do something useful here.

}

Use the addition assignment operator (+ =) to attach an event handler for the event. In the following example, suppose an object named publisher has an event named Raisecustomevent. Note that the Subscriber class needs to refer to the Publisher class to subscribe to its events.

Publisher. Raisecustomevent + = handlecustomevent;

Note that the syntax above is the new syntax in C # 2.0. It is exactly equivalent to the C # 1.0 syntax and you must explicitly create the encapsulated delegate using the following new keyword:

Publisher. Raisecustomevent + = new Customeventhandler (handlecustomevent);

subscribing to events using anonymous methods

Use the addition assignment operator (+ =) to attach an anonymous method to the event. In the following example, suppose an object named publisher has an event named Raisecustomevent, and a CustomEventArgs class is also defined to host certain types of private event information. Note that the Subscriber class needs to reference Publisher to subscribe to its events.

Publisher. Raisecustomevent + = Delegate (object o, CustomEventArgs e)

{

string s = o.tostring () + "" + e.tostring ();

Console.WriteLine (s);

};

Note that if you are using an anonymous method to subscribe to an event, the unsubscribe process for that event is more cumbersome. To unsubscribe at this point, return to the subscription code for the event, store the anonymous method in the delegate variable, and then add the delegate to the event.

Cancel Subscription

To prevent an event handler from being invoked when an event is raised, you simply unsubscribe from the event. To prevent resource leaks, it is important that you unsubscribe from events before releasing the Subscriber objects. Before canceling a subscription event, the multicast delegate that is the basis of the event in the publication object references the delegate that encapsulates the subscriber's event handler. No garbage collection is performed on a Subscriber object as long as the publication object contains the reference.

To unsubscribe from an event by using the subtraction assignment operator (-=):

Publisher. Raisecustomevent-= handlecustomevent;

When all Subscribers unsubscribe from an event, the event instance in the Publisher class is set to NULL.

Implementation of custom events

The following is a reference to sam1111 's blog post with the address:

Http://blog.csdn.net/sam1111/archive/2002/04/15/9773.aspx

event handling in C # is actually a delegate with a special signature, as follows:

public delegate void MyEventHandler (object sender, MyEventArgs e);

Of these two parameters, sender represents the event sender, and E is the event argument class. The MyEventArgs class is used to contain event-related data, and all event parameter classes must derive from the System.EventArgs class. Of course, if your event does not contain parameters, then you can use the System.EventArgs class as an argument directly.

The implementation of custom events can be summed up in the following steps:

1. Defines the event argument class, which should derive from the System.EventArgs class. If the event takes no arguments, this step can be omitted and go directly to step 3. Declare the class in a range visible to both the Publisher and Subscriber classes, and add the members that are required to retain the custom event data.

2. Declares a delegate that has two arguments, the first argument is the event sender object, and the second parameter class object.

3. Declare an event in the publication class. The event keyword is used to define an object, and it is also a delegate object.

4. Write the event trigger method in the form of a call to delegate where events need to be triggered in the publishing class. In general, this method should be a protected access restriction that cannot be invoked as public, but can be inherited by the quilt class. The name is OnEventName.

5. Define an event-handling method in the Subscriber class that should have the same parameter and return value type as the delegate object.

6. Add an event to the event queue with the + = operator in the Subscriber class (The-= operator can remove the event from the queue).

7. Invoke the event trigger method to trigger the event where appropriate.

The following is a simple example:

Using System;

Namespace Event

{

Step 1, define the event parameter class

public class Myeventargs:eventargs

{

private string message;

<summary>

Information

</summary>

public string Message

{

get {return message;}

}

//

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.