A simplest C # event example

Source: Internet
Author: User

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.

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.