C # deep understanding of event design and usage

Source: Internet
Author: User

Related Concepts 

Definition: an event is a type member used to notify other objects that a specific event has occurred to this object.
Note: An event is a member of the. NET type that is relatively difficult to understand and practice, because the event definition is not inherited from the basic data type, but encapsulation of the delegate (delegate. Therefore, before learning about events, you need to know a little about delegation.
Application Scenario: events are used in a wide range of scenarios. The most common scenario is the design of a large number of trigger events in various front-end controls. The reason is that
Significance: the use of event members is conducive to the implementation of object-oriented principles in the program. For example, the single responsibility principle of the type and the reversal principle of control. Imagine that if the front-end control cannot abstract a large number of rich events, it is almost impossible to decouple the front-end UI elements from the business logic. The program must be highly coupled.
Application of the design pattern: The Observer Pattern in the classic design pattern relies heavily on the design of event members.
This chapter analyzes the design of the event provider and subscriber type by designing an event triggering scenario when an email arrives. The case is from CLR Via C.

Design of event provider type

1. Define types to accommodate all additional information to be sent to event subscribers

Objective: To define a type for transmitting information to the event subscriber.
Method: Inherit the default System. EventArgs type to implement simple fields, attributes, and instance constructor members that need to pass information. Example:
Copy codeThe Code is as follows:
Using System;
Using System. Linq;

Namespace ConsoleTest
{
Public class NewMailEventArgs: EventArgs
{
Private readonly string from, to, subject;

Public NewMailEventArgs (string from, string to, string subject)
{
This. from = from;
This. to =;
This. subject = subject;
}

Public string Subject
{
Get
{
Return this. subject;
}
}

Public string
{
Get
{
Return this.;
}
}

Public string From
{
Get
{
Return this. from;
}
}
}
}

Ii. Define event members

Purpose: Define an event member in the event provider type for event subscriber object registration.
Method: encapsulate a custom delegate to provide a template for event processing methods, or implement a System. EventHandler generic type to achieve the same effect. (EventHandler is a default provided encapsulated delegate ). Examples of the two methods are as follows:
Method 1:

Copy codeThe Code is as follows:
Public delegate void NewMailHandler (object e, NewMailEventArgs args );

Public class MailManager
{
Public event NewMailHandler NewMail;
}

Method 2:
Copy codeThe Code is as follows:
Public class MailManager
{
Public event EventHandler <NewMailEventArgs> NewMail;
}

Why can these two methods achieve the same effect? Check the definition of System. EventHandler:
Copy codeThe Code is as follows:
Namespace System
{
// Summary:
// Indicates the method for processing the event.
//
// Parameters:
// Sender:
// Event source.
//
// E:
// A System. EventArgs containing event data.
//
// Type parameter:
// TEventArgs:
// The type of event data generated by the event.
[Serializable]
Public delegate void EventHandler <TEventArgs> (object sender, TEventArgs e );
}

3. Define a unified event trigger Method Portal to notify the event subscription object

Objective: define a method member in the event provider type to uniformly trigger the target event.
Note: To ensure that this method can only be called in this type and derived type, we need to modify the method to protected. In order to allow the derived type to override this method, we need to modify this method to virtual
Significance: This unified entry method is used to maintain the event triggering method and ensure the thread security of event calls. (Avoid synchronizing the status of event subscribers when different threads are triggered)
Example:

Copy codeThe Code is as follows:
Public class MailManager
{
Public event EventHandler <NewMailEventArgs> NewMail;

Protected virtual void OnNewMail (NewMailEventArgs e)
{
// For thread security considerations, copy the reference to the delegate field to a temporary field
EventHandler <NewMailEventArgs> temp = System. Threading. Interlocked. CompareExchange
(Ref NewMail, null, null );

// If an event subscriber object exists, notify them that the event has been triggered
If (temp! = Null)
Temp (this, e );
}
}

4. Call the method defined in step 3 in all business methods that need to trigger the event

Objective: there is also a business method in the type to convert the business scenario into event-triggered ..
Method: In any required business method, you can directly call the method in step 3, but you need to encapsulate a type of information passing.
Example:

Copy codeThe Code is as follows:
Public class MailManager
{
Public event EventHandler <NewMailEventArgs> NewMail;

Protected virtual void OnNewMail (NewMailEventArgs e)
{
// For thread security considerations, copy the reference to the delegate field to a temporary field
EventHandler <NewMailEventArgs> temp = System. Threading. Interlocked. CompareExchange
(Ref NewMail, null, null );

// If an event subscriber object exists, notify them that the event has been triggered
If (temp! = Null)
Temp (this, e );
}

Public void SimulateNewMail (string from, string to, string subject)
{
// Construct an object to encapsulate the information sent to the event subscriber.
NewMailEventArgs e = new NewMailEventArgs (from, to, subject );

// Method for triggering the event
OnNewMail (e );
}
}

Design of event subscriber type

1. Define types to subscribe to and listen to events

Objective: To design a Fax class for listening for NewMail events.
Note: You must subscribe to and unsubscribe to NewMail events in the Fax type. Example:
Copy codeThe Code is as follows:
Internal sealed class Fax
{
Private MailManager mailManager;

Public Fax (MailManager mm)
{
This. mailManager = mm;
}

Public void Register ()
{
MailManager. NewMail + = new EventHandler <NewMailEventArgs> (FaxMsg );
}

Void FaxMsg (object sender, NewMailEventArgs e)
{
Console. WriteLine ("Fax mail message ");
Console. WriteLine ("From = {0}, To = {1}, Subject = {2}", e. From, e. To, e. Subject );
}

Public void Unregister ()
{
MailManager. NewMail-= FaxMsg;
}
}

Related Article

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.