Some Beginners always find it difficult to learn events. In fact, they can start with a simple process. Although it is simple, it contains the entire process of the event mechanism. They need to think about it and then expand it, it's easier to learn.
In this example, there are only two classes, one is the event sending class Sender, and the other is the event receiving Class worker. Sender is responsible for sending an Event, and the Receiver is responsible for receiving and processing the Event.
Let's first look at the Sender class:
Public class Sender
{
Public delegate void EventHandler (object sender );
Public event EventHandler Event;
Public void TriggerEvent ()
{
Console. WriteLine ("Trigger an event .");
Event (this );
}
} First define a delegate EventHandler, then define an event and associate it with the delegate EventHandler. Next, trigger the Event (this); then let's look at the Cycler class: class Cycler
{
Public Receiver Er (Sender sender)
{
Sender. Event + = new Sender. EventHandler (OnEvent );
}
Private void OnEvent (object sender)
{
Console. WriteLine ("Received and handled an event .");
Console. Read ();
}
} Chain the Event triggered by the Sender class into the Event processing queue, specify the method for processing the Event, and process the Event. The whole process is so simple. For simplicity, the handler simply prints a sentence without setting parameters in the event. However, we can use this simple example to sort out the use of events.