. NET Foundation Supplements (4) Delegate and event 2

Source: Internet
Author: User

Event

An event is a message sent by an object that signals the occurrence of a notification operation. The operation may be caused by user interaction (such as a mouse click) or by some other program logic.

The object that raises the event is called the event sender. The object that captures the event and responds to it is called the event receiver.

In event communication, the event sender class does not know which object or method will receive (process) the event it raises. What is needed is a medium (or a mechanism similar to a pointer) between the source and the receiver.

The. NET Framework defines a special type (Delegate) that provides functionality for function pointers.

Microsoft product documentation defines an event: An event is a member that enables an object or class to provide notification .

public class Consoleeventargs:eventargs {//console output message private string message;            public string Message {get {return Message; }} public Consoleeventargs (): Base () {This.message = string.        Empty;        Public Consoleeventargs (String message): Base () {this.message = message; }}///<summary>////management console, sending output events before output///</summary> public class Consolemanager {//definition        Console event Member object public event eventhandler<consoleeventargs> consoleevent;             <summary>///console output///</summary> public void Consoleoutput (String message) {            Send event Consoleeventargs args = new Consoleeventargs (message);            Sendconsoleevent (args);        Output Message Console.WriteLine (msg); }//<summary>/Responsible for sending events///</summary>//<param name= "args" > Event parameters </param> protected virtual Voi D sendconsoleevent (Consoleeventargs args) {//define a temporary reference variable to ensure that there is no problem with multithreaded access Eventhandler<con            soleeventargs> temp = consoleevent;            if (temp! = null) {temp (this, args);         }}}///<summary>///log type, responsible for subscribing to console output events///</summary> public class Log {//log file        Private Const string logFile = @ "C:\TestLog.txt"; Public Log (Consolemanager cm) {//Subscription console output event cm. Consoleevent + = this.        Writelog; }///<summary>///Event handling method, note the parameter fixed mode///</summary>//<param name= "Sender" > Event Sender </param>///<param name= "args" > event parameters </param> private void Writelog (object sender, E Ventargs args) {//The file does not exist if a new file is created if (! File.exists (LOGFILe)) {using (FileStream fs = File.create (LogFile)) {}} FileInfo fi = NE            W FileInfo (LogFile); using (StreamWriter sw = fi.                AppendText ()) {Consoleeventargs CEA = args as Consoleeventargs; Sw. WriteLine (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss") + "|" + sender. ToString () + "|" + CEA.            Message); }}}class program {static void Main (string[] args) {//console event manager Consol            Emanager cm = new Consolemanager ();            Console Event Subscriber Log log = new log (cm); Cm.            Consoleoutput ("Test Console output event"); Cm.            Consoleoutput ("Test Console output event"); Cm.            Consoleoutput ("Test Console output event");        Console.readkey (); }    }

  

The event and the delegation of God horse contact?

It is often said that the nature of a delegate is a type, and the nature of the event is an instance of a particular delegate type. The best way to do this is to look at the original code and the compiled IL Code for analysis.

① Review Just the code that defines an event member in the Consolemanager class

public event eventhandler<consoleeventargs> Consoleevent;

EventHandler is a standard event pattern that is provided in the. NET Framework.

② the IL Code (intermediate Code) of the event consoleevent is shown below through reflector to make it easier to see this:

First, look at the IL code for EventHandler, and you can see that when the C # compiler compiles the delegate code, it is compiled as a class.

Second, when the C # compiler compiles the event code, it first adds a Eventhandler<t> delegate instance object to the type, and then adds a pair of add/remove methods to it to implement the ability to add and remove methods from the delegate chain.

By looking at the IL Code of add_consoleevent, you can clearly see that the nature of the subscription event is to call delegate's combine method to bind the event-handling method to the delegate chain .

 

. NET Foundation Supplements (4) Delegate and event 2

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.