C # event sender and receiver (subscriber)

Source: Internet
Author: User
C # event sender and receiver (subscriber)

Windows-based applications are message-based. Windows uses predefined messages to communicate with applications.
. NET Framework encapsulates Windows messages in events and uses events as the communication medium between objects.

Event Sender: the object that sends the event
Event receiver: the object that captures the event and responds to it (processing the event)
In the event communication mechanism, the event Sender does not know which object will receive the event and what kind of processing the event.
The sender does not know who will be the event receiver. It only broadcasts the message "event occurred.

In C #, the event mechanism is implemented by delegation. An event is equivalent to a delegated instance.

----------------------------------------------------------------------

Use event: There are four steps to use the event, which is slightly different from using the delegate.
1. Define a delegate type.
This step is no different from the use of delegation, generally using. Net pre-defined delegation.

2. Define an event name (in the event sender ).
Access Controller event Delegate type name event name;

3. encapsulate the event to register the event processing method to the event (the event processing method is defined in the event recipient ).
Event sender. event name + = new delegate type name (event processing method );

The event name is equivalent to the delegated Instance name, and the event processing method is equivalent to the associated method of the delegated instance. However, in the event mechanism, the definition of the delegated instance (the second step using the delegated) is divided into two steps, respectively by the event sender and receiver: define an event name-get a delegate instance name (event sender); encapsulate the event-Get an association method (associate an event processing method with an event) (event receiver ).
Note: When the event sender defines the event name, the event name can be identified as static, so that the event receiver can encapsulate the event

4. When the event sender triggers an event, the event receiver's event processing method captures and processes the event.
Triggering an event (equivalent to calling a delegated instance) will lead to the execution of the event processing method (equivalent to the execution of the associated methods of the delegated instance)
Events may be triggered by user operations (such as clicking the mouse) or by some other program logic;

--------------------------------------------------------------------
?
Using System;

Namespace EventExample
{
Class ClassReceive // event Receiver
{
[STAThread]
Static void Main (string [] args)
{
ClassSend Send = new ClassSend ();

// 3. encapsulate events
Send. CalculateFinished + = new MyDelegate (Send_CalculateFinished );

// Execute the following three rows, which will trigger the CalaculatedFinished event of MyClass three times.
Send. Square (2); // call the code of the event sender, causing the event to be triggered
Send. Cube (2); // call the code of the event sender, causing the event to be triggered
Send. Double (2); // call the code of the event sender, causing the event to be triggered
Console. Readline ();
}
// Define the event handling method and execute it after the event is triggered
Private Static void send_calculatefinished (string MSG)
{
Console. writeline (MSG + "computing completed ");
}
}

// 1. Define the delegate and specify the return type and parameter list. Same as the class definition, it is in the same namespace
Delegate void mydelegate (string MSG );

Class classsend // event sender
{
// 2. Define the event calculatefinished, which belongs to the myclass class
Public event mydelegate calculatefinished;

// 4. Execution of this method event will be triggered. Generally, the event Receiver calls this method to trigger the event.
Public void oncalculatefinished (string MSG)
{
// Determines whether the event is empty. If the event receiver defines the event processing method, the event is not null.
If (calculatefinished! = NULL)
{
// If the event is empty, an empty reference exception is triggered.
CalculateFinished (msg );
// The event triggered by this sentence, that is, the event name (form parameter list );
// The parameter list of this method has been specified by the event-related delegate.
}
}

Public void Square (float x)
{
Float result = x * x;
Console. WriteLine ("{0}'s square equals: {1}", x, result );
// Execute the event triggering method, which will cause the event to be triggered
OnCalculateFinished ("square ");
}
Public void Cube (float x)
{
Float result = x * x;
Console. WriteLine ("the cube of {0} is equal to: {1}", x, result );
// Execute the event triggering method, which will cause the event to be triggered
OnCalculateFinished ("cube ");
}
Public void Double (float x)
{
Float result = 2 * x;
Console. writeline ("a multiple of {0} is equal to: {1}", X, result );
// Execute the event triggering method, which will cause the event to be triggered
Oncalculatefinished ("multiple ");
}
}
}

--------------------------------------------------------------------

An event is a multi-point delegate. Only the + = and-= operations can be used for the event. The = operation is invalid for the event.

. NET provides a predefined event Delegate type-eventhandler
Public Delegate void eventhandler (Object sender, eventargs E );
The sender parameter is the event sender object that triggers the event, and E is the event-related data.
When defining an event, you can directly use this predefined event Delegate type without having to customize the delegate type.

Custom events must comply with naming rules:
It is best to use the verb naming event to describe the trigger timeliness of the event with the current, ongoing, or completed tense;
The name of the event Delegate type is generally suffixed with "eventhandler" and the name of the event parameter class is suffixed with "eventargs;
Always use sender and E to name two parameters in the event;
In the event sender, the method for triggering the event is generally named on + event name eg: oncalaculatefinished (string MSG );

In the event sender class, when defining the method for triggering the event (including the statement for calling the event), you must first determine whether the event is empty, because events are encapsulated in the recipient (defining the event processing method), the event sender cannot know whether there is an event processing method (the sender does not know the recipient's existence ), therefore, in the Code where the event is triggered by the event sender, you must first determine whether the event is empty. In addition, the event receiver often calls the code of the event sender, which causes the event to be triggered. Therefore, in the event receiver, the code that encapsulates the event should be executed before the code that calls the event sender.

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.