When an event is triggered, the method for subscribing to the event is executed in the thread that triggers the event. That is to say, the method for subscribing to this event is synchronously executed in the thread that triggers the event. Therefore, there is a problem: if the method to subscribe to an event takes a long time to execute, the thread that triggers the event is blocked, and the method execution is completed for a long time. In this way, not only the execution of subsequent subscription event methods is affected, but also the primary thread responds to other user requests in a timely manner. How can this problem be solved? At this point, I think you have come up with an asynchronous event call.
How to Implement Asynchronous event calling? If you know more about events, you should know that the nature of events is actually a multicastdelegate ). The multicastdelegate class provides a getinvocationlist method, which returns the array of delegate calls of this multicast delegate. This method can be used to implement the asynchronous event calling function.
Sample Code:
Using system; using system. threading; using system. runtime. remoting. messaging; namespace processtest {class program {// defines an event public static event eventhandler <eventargs> onevent; // method 1 static void Method1 (Object sender, eventargs E) {// display the thread ID console that executes this method. writeline ("the thread ID for calling Method1 is: {0}", thread. currentthread. managedthreadid); thread. sleep (1000);} // method 2 static void method2 (Object sender, eventargs e) {console. writeline ("the thread ID for calling method2 is: {0}", thread. currentthread. managedthreadid); thread. sleep (1000);} static void main (string [] ARGs) {// displays the main thread ID system. console. writeline ("main thread ID: {0}", thread. currentthread. managedthreadid); // register Method1 and method2 to the event onevent + = new eventhandler <eventargs> (Method1); onevent + = new eventhandler <eventargs> (method2 ); // The following code calls events asynchronously. // gets the multi-channel delegate list in the event. Delegate [] delegary = onevent. getinvocationlist (); // traverses the delegate list foreach (eventhandler <eventargs> Deleg in delegary) {// asynchronously calls the delegate Deleg. begininvoke (null, eventargs. empty, null, null);} system. console. readkey ();}}}
The code execution result is as follows:
Observe the running results and you will find that the main thread ID, the thread ID that executes the Method1 function, and the thread ID that executes the method2 function are different. Therefore, we can see that asynchronous event calling is implemented.