C # uses delegates to implement asynchronous calls

Source: Internet
Author: User
Asynchronous

Asynchronous programming is a feature supported by many areas of the common language runtime, such as remoting, ASP.net, and Windows forms. Asynchronous programming is the core concept in the. NET Framework. Use. NET asynchronous programming to call the. NET class method at the same time as the program continues, until the specified callback is made, or if no callback is provided, until the call is blocked, polled, or waiting to be completed.

Asynchronous programming is a feature that is supported by many areas of the. NET Framework, including:

File io, stream io, socket IO
Network: HTTP, TCP
Remoting channels (HTTP, TCP) and proxies
XML Web Services created using asp.net
asp.net Web forms
Message Queuing using the MessageQueue class
Asynchronous delegates
The. NET Framework allows you to invoke any method asynchronously. Defines a delegate with the same signature as the method that needs to be invoked; The common language runtime automatically defines the BeginInvoke and EndInvoke methods with the appropriate signature for that delegate.

The BeginInvoke method is used to initiate an asynchronous call. It has the same parameters as the method that needs to be executed asynchronously, except that there are two additional parameters (which will be described later). BeginInvoke immediately returns without waiting for the asynchronous call to complete. BeginInvoke returns IasyncResult, which can be used to monitor call progress.
The EndInvoke method is used to retrieve the results of an asynchronous call. You can call the EndInvoke method at any time after calling BeginInvoke, and EndInvoke will block until the asynchronous call completes if the asynchronous call is not completed. The EndInvoke parameters include the out and ref parameters of the method that need to be executed asynchronously and the IAsyncResult returned by BeginInvoke.
After the BeginInvoke is invoked, you can:

Do something, and then call EndInvoke to block until the call completes.
Using IAsyncResult.AsyncWaitHandle to get WaitHandle, use its WaitOne method to block execution until the WaitHandle signal is emitted, and then call EndInvoke.
Polls the IAsyncResult returned by BeginInvoke to determine when the asynchronous call completes and then calls EndInvoke.
The delegate used for the callback method is passed to the BeginInvoke. This method executes on the ThreadPool thread after the asynchronous call completes, and it can invoke EndInvoke.
The following is an example of using a delegate to invoke an asynchronous method. An AddDelegate type delegate add is first defined in the instance and the method add is bound to the delegate instance. The IAsyncResult interface type instance IAR is then defined and the BeginInvoke method that invokes the delegate add is used to initiate the asynchronous invocation. Because a WaitHandle signal is emitted when the asynchronous call completes, it is possible to wait for it through the IAR.AsyncWaitHandle.WaitOne (), during which the main program can perform some additional tasks to achieve the effect that the program executes asynchronously. Finally, the EndInvoke method is called to retrieve the results of the asynchronous call. It is noteworthy that if an asynchronous call is not completed, EndInvoke will block until the asynchronous call completes.

Using System;
Using System.Threading;

Example of using a delegate to invoke an asynchronous method
Namespace Delegatecallasynchronousmethods
... {

    class asyncdelegatesblocked
    ... {
        public static int Add (int op1, int op2, out int result)
  & nbsp;     ... {
            thread.sleep (3000);//simulating work
            return (result = OP1 + OP2);
       }
        Public delegate int adddelegate (int op1, int op2,
             out int result);//Declaration AddDelegate Delegate

static void Main ()
... {
int result;
/**//* defines a AddDelegate type delegate add, which binds the method add to the delegate instance.
AddDelegate add = new AddDelegate (add);

Console.WriteLine ("[Main] invoking the asynchronous" +
"Add method");

           /**//*BeginInvoke method is used to initiate an asynchronous call. It has the same parameters as the method you need to execute asynchronously, and there are two additional parameters
             * BeginInvoke immediately returns without waiting for the asynchronous call to complete. BeginInvoke returns IasyncResult, which can be used to monitor call progress. */
           
            //Define IAsyncResult interface type instance IAR
            //6, out of the argument list for a method that is executed asynchronously
             IAsyncResult IAR = Add. BeginInvoke (6, $, out result, 
                 null, NULL);

           //Here we ' re Simulating doing some work before
           //Blocking On the Add method ' s completion.
            Console.Write ("[Main] doing other work");
            for (int i = 0; i < i++)
  & nbsp;         ... {
                thread.sleep ( 200);
                Console.Write (".");
           }

            Console.WriteLine ("[ Main] Waiting for ADD to finish ");
           /**//* use IAsyncResult.AsyncWaitHandle to obtain WaitHandle,
             * use its WaitOne Method blocks the execution until the WaitHandle signal is emitted, and then calls EndInvoke.
             * Note: A WaitHandle signal is emitted when the asynchronous call completes. You can wait for it through WaitOne */
            IAR.AsyncWaitHandle.WaitOne ();

Console.WriteLine ("[Main] Add finished, cleaning up");
The/**//*endinvoke method is used to retrieve the results of an asynchronous call. The EndInvoke method can be invoked at any time after calling BeginInvoke;
* If the asynchronous call is not completed, EndInvoke will block until the asynchronous call completes.
* EndInvoke parameters include the out and ref parameters of the method to be executed asynchronously and the IAsyncResult returned by BeginInvoke. */
Add. EndInvoke (out result, IAR);

Console.WriteLine ("[Main] The result is {0}", result);
Console.ReadLine ();
}
};

}



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.