C # event design and use deep understanding _ practical skills

Source: Internet
Author: User
Related Concepts

Definition: An event is a type member that notifies other objects of the occurrence of a particular event in this object.
Description: The event is. NET type member is relatively difficult to understand and practice, because the definition of the event is not inherited from the underlying data type, but rather the encapsulation of the delegate (delegate). So before you know the event, you need to know a little about the delegate.
Scenario: Events are widely used, and the most common scenario is a large number of trigger event designs in the various front-end controls. Reason is because
Significance: The use of event members facilitates the implementation of object-oriented principles in programs. For example, type of single duty principle, control reversal principle. Imagine that if a 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. Programs must be highly coupled.
Application of design pattern: The Observer pattern in the classic design pattern is very dependent on the design of the event member.
This chapter resolves the design of event providers and Subscriber types by designing a scenario that triggers events when an e-mail arrives. The case comes from the "CLR Via C #" book.

design of event provider types

I. Define types to accommodate all additional information that needs to be sent to event subscribers

Goal: Define a type to pass information to the subscriber of the event
Method: Inherits the default System.EventArgs type, implements a simple field that needs to be passed information, attributes, and instance constructor members. Examples are as follows:
Copy Code code 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 = to;
This.subject = subject;
}

public string Subject
{
Get
{
return this.subject;
}
}

public string to
{
Get
{
return this.to;
}
}

public string from
{
Get
{
return this.from;
}
}
}
}

Two. Defining Event Members

Goal: Define an event member in the event provider type for the registration of the event subscriber object.
Method: Encapsulates a custom delegate to provide the template for the event-handling method, or implements a System.EventHandler generic type to achieve the same effect. (EventHandler is a encapsulated delegate that is provided by default). Examples of the two methods are as follows:
Method One:

Copy Code code as follows:

public delegate void Newmailhandler (Object E, Newmaileventargs args);

public class Mailmanager
{
public event Newmailhandler NewMail;
}

Method Two:
Copy Code code as follows:

public class Mailmanager
{
public event eventhandler<newmaileventargs> NewMail;
}

Why do these two methods achieve the same effect, look at the definition of System.EventHandler to know:
Copy Code code as follows:

Namespace System
{
Summary:
Represents the method that will handle the event.
//
Parameters:
Sender
The source of the event.
//
E:
A System.EventArgs that contains the event data.
//
Type parameters:
Teventargs:
The type of event data generated by the event.
[Serializable]
public delegate void Eventhandler<teventargs> (object sender, Teventargs e);
}

three. Define a method portal that triggers the event to notify the subscription object of the event

Goal: Define a method member in the event provider type that is used to uniformly raise the target event.
Note: To ensure that this method can only be invoked in this and derived types, we need to modify the method to protected so that the derived type can override this method, we need to modify the method to virtual
Meaning: The purpose of this unified approach is to be able to maintain a unified approach to triggering events and to ensure the thread safety of event calls. (Avoid the state of the event subscriber from synchronizing when different threads are fired)
Examples are as follows:

Copy Code code as follows:

public class Mailmanager
{
public event eventhandler<newmaileventargs> NewMail;

protected virtual void Onnewmail (Newmaileventargs e)
{
For thread-safe consideration, the reference to the delegate field is now copied to a temporary field
eventhandler<newmaileventargs> temp = System.Threading.Interlocked.CompareExchange
(ref NewMail, NULL, NULL);

If there are event subscriber objects, notify them that the event has been triggered
if (temp!= null)
Temp (this, e);
}
}

four. In all business methods that need to trigger the event, invoke the method defined in step three

Objective: There is also a need for a business approach in the type to turn the scenarios in the business into event triggers.
Method: In any desired business method, it is OK to call the third step directly, but you need to implement a type that encapsulates a passing message.
Examples are as follows:

Copy Code code as follows:

public class Mailmanager
{
public event eventhandler<newmaileventargs> NewMail;

protected virtual void Onnewmail (Newmaileventargs e)
{
For thread-safe consideration, the reference to the delegate field is now copied to a temporary field
eventhandler<newmaileventargs> temp = System.Threading.Interlocked.CompareExchange
(ref NewMail, NULL, NULL);

If there are event subscriber objects, notify them that the event has been triggered
if (temp!= null)
Temp (this, e);
}

public void Simulatenewmail (string from, string to, string subject)
{
Constructs an object to encapsulate the information passed to the event subscriber
Newmaileventargs e = new Newmaileventargs (from, to, subject);

The entry method that triggers the event trigger
Onnewmail (e);
}
}

Event Subscriber Type design

I. Defining types to subscribe and listen for events

Objective: To design a fax type to listen for NewMail events.
Note: You need to have a subscription and unsubscribe method for the NewMail event in the fax type. Examples are as follows:
Copy Code code 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;
}
}

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.