Asynchronous programming
- Synchronous programming, request response model, synchronous, sequential, transactional.
- Asynchronous programming, event-driven model, implemented in fire and forget mode.
Asynchronous Programming patterns
? -§-? Asynchronous programming Model (APM) mode: IAsyncResult mode, the asynchronous operation requires a Begin and End method;
? -§-? Event-based Asynchronous mode (EAP): event, event handler delegate type, and EventArg derived type;
? -§-? Task-based Asynchronous mode (TAP): Recommended mode, introduced in. NET Framework 4, based on the System.Threading.Tasks namespace, using a method to represent the start and completion of asynchronous operations;
The class LogicalMethodInfo provides methods for the Invoke and BeginInvoke methods that support synchronous or asynchronous execution of delegates:
public sealed class system.web.services.protocols.logicalmethodinfo{public object[] Invoke (object target, Object [] values); Public IAsyncResult BeginInvoke (object target, object[] values, AsyncCallback callback, Object asyncstate); Public object[] EndInvoke (object target, IAsyncResult asyncResult); }
Where target is the class instance to which the delegate method belongs, and values is the argument list of the delegate method.
Asynchronous method Invocation Pattern
? Three methods call pattern differences: The original thread gets the way the asynchronous thread has completed the message.
?
? Where the BeginInvoke method is used to initiate an asynchronous call, the EndInvoke method is used to retrieve and obtain the asynchronous call result and then release the resource that the thread occupies. BeginInvoke returns immediately without waiting for the asynchronous method call to complete, while creating a AsyncResult class object at the time of invocation, but BeginInvoke returns a reference to the IAsyncResult interface that can be used to monitor the call progress of an async method, calling The EndInvoke method can be called at any time after BeginInvoke.
?
? Where the AsyncState property of the IAsyncResult interface gets an object of type objects that can be used as the state parameter when the BeginInvoke method is called (customizable as needed). The delegate definition and the asynchronous delegate method are defined as:
public delegate int Mydel (string str); public static int Delfun (String str) {Console.WriteLine ("Async Thread Execution Method: Delfun () in" + Thread.CurrentThread.ManagedThreadId) ; Thread.Sleep (3000); Return str. Length; }
Note : The parameters of BeginInvoke are dynamically generated at compile time according to the definition of the delegate, the number and type of the preceding arguments are the same as the number and type of arguments in the delegate definition, and the latter two are the AsyncCallback and the Object types respectively. The method list of the caller of the BeginInvoke has and can only have one method. BeginInvoke The third parameter can be any type, and eventually the corresponding value can be obtained through the AsyncState property.
Wait Mode Waiting-until-done
If the asynchronous method call is not completed, EndInvoke will block until the asynchronous method call finishes. Among them, waiting for WaitHandle is a common thread synchronization technique that can be called by the AsyncWaitHandle property of the IAsyncResult returned by BeginInvoke to block the current thread by calling the WaitOne () method. The WaitHandle signal that is emitted until the asynchronous method call is completed.
public static void Asyncwaitingtest () { Mydel Mydel = new Mydel (testclass.delfun); Console.WriteLine ("Main thread: Asyncwaitingtest () in" + Thread.CurrentThread.ManagedThreadId); IAsyncResult IAR = Mydel.begininvoke ("SQH", NULL, NULL); Console.WriteLine ("Main thread continues to execute ... in" + Thread.CurrentThread.ManagedThreadId); while (!iar. Asyncwaithandle.waitone (+) {Console.WriteLine ("Waiting ... Asyncmethod () "); } int strLen = Mydel.endinvoke (IAR); Console.WriteLine ("Str length:{0}", StrLen); }
Polling mode Polling
Use the IsCompleted property of the IAsyncResult returned by BeginInvoke to determine whether the asynchronous method call is complete.
public static void Asyncpollingtest () {Mydel Mydel = new Mydel (testclass.delfun); Console.WriteLine ("Main thread: Asyncpollingtest () in" + Thread.CurrentThread.ManagedThreadId); IAsyncResult IAR = Mydel.begininvoke ("SQH", NULL, NULL); Console.WriteLine ("Main thread continues to execute ... in" + Thread.CurrentThread.ManagedThreadId); while (!iar. iscompleted) {thread.sleep (1000); Console.WriteLine ("Waiting ... Asyncmethod () "); } int strLen = Mydel.endinvoke (IAR); Console.WriteLine ("Str length:{0}", StrLen); }
Callback Mode Callback
The callback method is provided when BeginInvoke is called, and the callback method executes automatically on the asynchronous thread in ThreadPool and calls the EndInvoke method after the asynchronous method call ends.
The callback method is shaped as: void AsyncCallback(IAsyncResult IAR);
public static void Asynccallbacktest () {Mydel Mydel = new Mydel (testclass.delf UN); Console.WriteLine ("Main thread: Asynccallbacktest () in" + Thread.CurrentThread.ManagedThreadId); IAsyncResult IAR = Mydel.begininvoke ("Sqh", Callbackmethod, Mydel); Console.WriteLine ("Main thread continues to execute ... in" + Thread.CurrentThread.ManagedThreadId); // ... Other operations, independent of Async thread} public static void Callbackmethod (IAsyncResult iar) {Console.WriteLine ("Async method execution completed, start execution callback method in" + Thread . Currentthread.managedthreadid); AsyncResult ar = (AsyncResult) IAR; * * Recommended * *//mydel Mydel = (mydel) ar. AsyncDelegate; Mydel Mydel = (mydel) IAR. asyncstate; This method of invocation BeginInvoke requires the Mydel parameter int result = Mydel.endinvoke (IAR); Console.WriteLine (result); }
other : When there are multiple methods in the delegate's method list, you can take advantage of the Getinvocationlist () method to get the delegate[] array, and then call the BeginInvoke method in turn, running different methods on different threads of the online pool!
Reference
[1]. Asynchronous Programming Mode series (1-6);
[2]. Asynchronous method invocation pattern summary; asynchronous invocation of four methods;
C #-Multi-thread asynchronous programming