Delegate Threading Trilogy (citation)

Source: Internet
Author: User

#异步委托 (asynchronous method call) One: synchronous invocation: The execution of the program is time-consuming [method]--> blocking the current thread-->[method] Call finish--continues execution. Asynchronous invocation:--------------------------------------------------------------------------------Delegate Example: The self-write delegate is as follows: public dele    Gate string MyDelegate (string name);    Microsoft will automatically provide the following two methods: IAsyncResult BeginInvoke (String name, AsyncResult callback, Object O); String EndInvoke (IAsyncResult result);--------------------------------------------------------------------------    ------Each delegate has 3 methods: Invoke: Is the synchronous invocation of the delegate-specified function; BeginInvoke: is an asynchronous call that returns immediately after the call and does not wait for the call result EndInvoke: is an asynchronous call that is used to retrieve the call result. Called after BeginInvoke can be called at any time, it will block until the asynchronous call is complete. AsyncCallback delegate: Used to specify the method that should be called after the start operation is complete. IAsyncResult interface: Used to monitor and manage asynchronous operations.              public interface iasyncresult{Object asyncstate {get;}     The property is the last Parameter object in the BeginInvoke parameter WaitHandle asyncwaithandle {get;}    BOOL completedsynchronously {get;}    If the start operation call has been synchronized, its properties will be set to true.               BOOL iscompleted {get;} This property determines whether the asynchronous call ends}--------------------------------------------------------------------------------Example: 1) Define a delegate: using System.Threading;    Using System.Runtime.Remoting.Messaging;    public delegate int AddHandler (int a,int b);  public class addition class {public static int Add (int a, int b) {Console.WriteLine ("Start calculation:" + A + "+" +            b); Thread.Sleep (3000); Simulate this method to run for three seconds Console.WriteLine ("Calculation done!            ");        return a + B; }}2) Synchronous invocation: The Invoke method of the delegate is used for synchronous invocation.    A synchronous call can also be called a blocking call, which blocks the current thread and then executes the call, and then continues down after the call is complete.             public class synchronous Call {static void Main () {Console.WriteLine ("===== Synchronous call Syncinvoketest ====="); AddHandler handler = new AddHandler (addition class.            ADD); int result = handler.            Invoke (1, 2); Console.WriteLine ("Keep doing something else ...            ");            Console.WriteLine (result);        Console.readkey ();         }/* Run Result: ===== Synchronous call Syncinvoketest ===== start calculation: 1+2 calculation is complete!         Continue to do other things ... 3 */}3) Asynchronous Call: Asynchronous call does not dragPlug the thread into the thread pool, and the program's main thread or UI thread can continue to execute.    The asynchronous invocation of a delegate is implemented by BeginInvoke and EndInvoke. public class asynchronous Call {static void Main () {Console.WriteLine ("===== Asynchronous call Asyncinvoketest =====")            ; AddHandler handler = new AddHandler (addition class.            ADD); IAsyncResult: Asynchronous Operation Interface (interface)//begininvoke: The start of an asynchronous method for a delegate (delegate) IAsyncResult result = Handle            R.begininvoke (1, 2, NULL, NULL); Console.WriteLine ("Keep doing something else ...            "); The asynchronous operation returns Console.WriteLine (handler.            EndInvoke (result));        Console.readkey ();         }/* Run Result: ===== asynchronously calls Asyncinvoketest ===== to continue doing something else ...         Start calculation: 1+2 calculation is complete!    3 */}4) Asynchronous callback: With a callback function, the callback function is automatically invoked at the end of the call, which resolves the situation where the thread is still blocked waiting for the result to be called. public class Async Callback {static void Main () {Console.WriteLine ("===== Async callback Asyncinvoketest =====")            ; AddHandler handler = new AddHandler (addition class.            ADD); Asynchronous operator interface (note the different BeginInvoke methods!)            )IAsyncResult result = handler.                        BeginInvoke (1,2,new AsyncCallback (callback function), "Asycstate:ok"); Console.WriteLine ("Keep doing something else ...            ");        Console.readkey (); The static void callback function (IAsyncResult result) {//result is the addition class. The return value of the ADD () method//asyncresult is an implementation class for the IAsyncResult interface, Space: System.Runtime.Remoting.Messaging//asyncdelegat            The E property can be cast to the actual class of a user-defined delegate. AddHandler handler = (AddHandler) ((AsyncResult) result).            AsyncDelegate; Console.WriteLine (handler.            EndInvoke (result)); Console.WriteLine (Result.        asyncstate);        }/* Run Result: ===== Asynchronous callback Asyncinvoketest ===== start calculation: 1+2 continue to do other things ...        Calculation done! 3 Asycstate:ok */} Summary: The Invoke method first checks whether the calling thread (that is, the current thread) is the UI thread, and if so, directly executes the method that the delegate points to, if not, it switches to the UI thread, and then executes the delegate that refers to the to the method.

Delegate Thread Trilogy (reference)

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.