C # asynchronous invocation and callback __c#

Source: Internet
Author: User
C # Asynchronous delegate (asynchronous method invocation): Synchronous invocation:--> invocation of a time-consuming method]--> blocking the current thread-->[method call completion--> continue execution. Asynchronous invocation:--------------------------------------------------------------------------------Delegate Example: self-write delegate as follows: Publi
    C Delegate 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 a delegate that specifies a function.
    Synchronous call; BeginInvoke: is an asynchronous call that returns immediately after the call and does not wait for the call result EndInvoke: is an asynchronous call to retrieve the call result.

Called BeginInvoke can be invoked at any time, and it will block until the asynchronous call completes.
AsyncCallback delegate: Used to specify the method that should be invoked after the start of the operation.

IAsyncResult interface: for monitoring and managing 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 action call is completed synchronously, its properties will be set to true.               BOOL iscompleted {get;} This property determines whether the asynchronous call ends}--------------------------------------------------------------------------------Example: 1 defines a delegate: using System.threa
    Ding

    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 run three seconds Console.WriteLine ("Compute complete.")
            ");
        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 downward after the call completes. public class synchronization Call {static void Main () {Console.WriteLine ("===== synchronous call Syncinvoketest = =
            ="); AddHandler handler = new AddHandler (addition class.
            ADD); int result = handler.

            Invoke (1, 2); Console.WriteLine ("Go on doing something else ...")

            ");
            Console.WriteLine (result);
        Console.readkey ();
   /* Run Result: ===== Synchronous call Syncinvoketest ===== start calculation: 1+2      The calculation is complete.
         Go on doing something else ... 3/} 3 asynchronous invocation: The asynchronous invocation does not block the thread, but instead plugs the call into the thread pool, and the program's main thread or UI threads can continue to execute.
    Asynchronous invocations of delegates are implemented through BeginInvoke and EndInvoke. The public class asynchronously calls {static void Main () {Console.WriteLine ("===== asynchronous call asyncinvoketest = = =
            =="); AddHandler handler = new AddHandler (addition class.

            ADD); IAsyncResult: Asynchronous Operation Interface (interface)//begininvoke: Start of an asynchronous method of a delegate (delegate) IAsyncResult result = Hand Ler.

            BeginInvoke (1, 2, NULL, NULL); Console.WriteLine ("Go on doing something else ...")

            "); The asynchronous operation returns Console.WriteLine (handler.
            EndInvoke (result));
        Console.readkey ();
         /* Run Result: ===== Asynchronous call Asyncinvoketest ===== continue to do something else ...
         Start calculation: 1+2 calculation complete.

    3/} 4 asynchronous callback: With a callback function, the callback function is automatically invoked at the end of the call, resolving the situation where the thread is still blocked for waiting for the result to be invoked. public class asynchronous callback {static void Main () {Console.WriteLine ("===== Asynchronous callback asyncinvoketest = = =
 ==");           AddHandler handler = new AddHandler (addition class.

            ADD); Asynchronous Operation Interface (note the difference between BeginInvoke methods). ) IAsyncResult result = handler.
            
            BeginInvoke (1,2,new AsyncCallback (callback function), "Asycstate:ok"); Console.WriteLine ("Go on doing something else ...")
            ");
        Console.readkey (); The static void callback function (IAsyncResult result) {//result is an additive class. The return value of the ADD () method//asyncresult is an implementation class for the IAsyncResult interface, Space: System.Runtime.Remoting.Messaging//asyncdele
            The gate property can be cast to the actual class of the 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 ...
        The calculation is complete. 3 Asycstate:ok/} Summary: The Invoke method first checks whether the calling thread (that is, the current thread) is not a UI thread, if it is, directly executes the method that the delegate points to, and if not, it switches to the UI thread, but The method that the delegate points to after execution.

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.