Reproduced C # asynchronous invocation four-way explanation

Source: Internet
Author: User

What are the four ways to call C # asynchronously? How does the use of the four methods of C # asynchronous invocation work? Let's start by knowing when to use the C # asynchronous call:

The. NET Framework allows you to call any method asynchronously in C #. Defines a delegate that has the same signature as the method you need to call; The common language runtime automatically defines the BeginInvoke and EndInvoke methods with the appropriate signatures for the delegate.

The BeginInvoke method is used to start a C # asynchronous call. It has the same parameters as the method you need to execute asynchronously, but there are two additional parameters (which will be described later). BeginInvoke immediately returns without waiting for the C # asynchronous call to complete. BeginInvoke returns IasyncResult, which can be used to monitor the call progress.

The EndInvoke method is used to retrieve C # asynchronous invocation results. The EndInvoke method can be called at any time after calling BeginInvoke, and if the C # asynchronous call is not completed, EndInvoke will block until the C # asynchronous call completes. The parameters of EndInvoke include the Out and ref parameters (ByRef and ByRef in Visual Basic) and the IAsyncResult returned by BeginInvoke that you need to execute asynchronously.

Note the IntelliSense feature in Visual Studio. NET Displays the parameters for BeginInvoke and EndInvoke. If you are not using Visual Studio or a similar tool, or if you are using C # and Visual studio. NET, see Async method signatures for a description of the parameters that the runtime defines for these methods.

The code in this topic demonstrates four common ways to make C # asynchronous calls using BeginInvoke and EndInvoke. Once you have called BeginInvoke, you can:

· Make some operations, and then call EndInvoke to block until the call is complete.

· Use 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, determines when the C # asynchronous call is completed, and then calls EndInvoke.

· The delegate that is used for the callback method is passed to BeginInvoke. This method executes on the ThreadPool thread after the C # asynchronous call completes, and it can call EndInvoke.

Warning: EndInvoke is always called after the C # asynchronous call completes.

Test methods and asynchronous delegates

All four examples use the same long-running test method TestMethod. The method shows a console message that indicates that it has started processing, sleeps for a few seconds, and then ends. TestMethod has an out parameter (ByRef in Visual Basic) that demonstrates how to add these parameters to the signatures of BeginInvoke and EndInvoke. You can work with the ref parameter in a similar way (ByRef in Visual Basic).

The following code example shows TestMethod and delegates representing TestMethod; To use any of the examples, append the sample code to this code.

Note In order to simplify these examples, TestMethod is declared in a class separate from Main (). Alternatively, TestMethod can be a static method in the same class that contains Main () (Shared in Visual Basic).

  1. usingSystem; usingSystem.Threading;  Public classAsyncdemo {//The method to is executed asynchronously. //   Public stringTestMethod (intCallduration, out intthreadId) {Console.WriteLine ("Test method begins.");  Thread.Sleep (callduration); ThreadId=Appdomain.getcurrentthreadid (); return "Mycalltime was"+callduration.tostring (); }  }   //The delegate must has the same signature as the method//You want-to-call asynchronously.  Public Delegate stringAsyncDelegate (intCallduration, out intthreadId); usingSystem; usingSystem.Threading;  Public classAsyncdemo {//The method to is executed asynchronously. //   Public stringTestMethod (intCallduration, out intthreadId) {Console.WriteLine ("Test method begins.");  Thread.Sleep (callduration); ThreadId=Appdomain.getcurrentthreadid (); return "Mycalltime was"+callduration.tostring (); }  }   //The delegate must has the same signature as the method//You want-to-call asynchronously.  Public Delegate stringAsyncDelegate (intCallduration, out intTHREADID);

C # Asynchronous invocation of four methods using EndInvoke to wait for an asynchronous call

The simplest way to execute a method asynchronously is to start with BeginInvoke, perform some action on the main thread, and then call EndInvoke. EndInvoke is not returned until the C # asynchronous call is complete. This technique is ideal for file or network operations, but because it blocks EndInvoke, do not use it from the service thread of the user interface.

  1.  Public classAsyncmain {Static voidMain (string[] args) {  //The asynchronous method puts the thread ID here. intthreadId; //Create An instance of the test class. Asyncdemo AD =NewAsyncdemo (); //Create the delegate. AsyncDelegate dlgt =NewAsyncDelegate (AD.       TestMethod); //Initiate the asychronous call. IAsyncResult ar = dlgt. BeginInvoke ( the,    outThreadId,NULL,NULL); Thread.Sleep (0); Console.WriteLine ("Main Thread {0} does some work.", Appdomain.getcurrentthreadid ()); //Call EndInvoke to Wait for//the asynchronous call to complete,//and to retrieve the results. stringret = dlgt. EndInvoke ( outthreadId, AR); Console.WriteLine ("the call executed on thread {0},WithreturnValue \"{1}\ ".", ThreadId, ret); }  } 

C # Asynchronous invocation of four methods using WaitHandle to wait for an asynchronous call

Waiting for WaitHandle is a common thread synchronization technique. You can use the AsyncWaitHandle property of the IAsyncResult returned by BeginInvoke to get the WaitHandle. The C # asynchronous call will emit a WaitHandle signal when it completes, and you can wait for it by calling its WaitOne.

If you use WaitHandle, you can perform additional processing after the C # asynchronous call is complete, but before you retrieve the results by calling EndInvoke.

  1.  Public classAsyncmain {Static voidMain (string[] args) {  //The asynchronous method puts the thread ID here. intthreadId; //Create An instance of the test class. Asyncdemo AD =NewAsyncdemo (); //Create the delegate. AsyncDelegate dlgt =NewAsyncDelegate (AD.       TestMethod); //Initiate the asychronous call. IAsyncResult ar = dlgt. BeginInvoke ( the,    outThreadId,NULL,NULL); Thread.Sleep (0); Console.WriteLine ("Main Thread {0} does some work.", Appdomain.getcurrentthreadid ()); //Wait for the WaitHandle to become signaled. ar.   Asyncwaithandle.waitone (); //Perform Additional processing here. //Call EndInvoke to retrieve the results. stringret = dlgt. EndInvoke ( outthreadId, AR); Console.WriteLine ("the call executed on thread {0},WithreturnValue \"{1}\ ".", ThreadId, ret); }  } 

C # Asynchronously invokes the four-way polling asynchronous call completion

You can use the IsCompleted property of the IAsyncResult returned by BeginInvoke to discover when a C # asynchronous call is completed. You can do this when you make a C # asynchronous call from a service thread in the user interface. Polling completion allows the user interface thread to continue processing user input.

  1.  Public classAsyncmain {Static voidMain (string[] args) {  //The asynchronous method puts the thread ID here. intthreadId; //Create An instance of the test class. Asyncdemo AD =NewAsyncdemo (); //Create the delegate. AsyncDelegate dlgt =NewAsyncDelegate (AD.       TestMethod); //Initiate the asychronous call. IAsyncResult ar = dlgt. BeginInvoke ( the,    outThreadId,NULL,NULL); //Poll while simulating work.  while(AR. IsCompleted = =false) {Thread.Sleep (Ten); }   //Call EndInvoke to retrieve the results. stringret = dlgt. EndInvoke ( outthreadId, AR); Console.WriteLine ("the call executed on thread {0},WithreturnValue \"{1}\ ".", ThreadId, ret); }  } 

C # Asynchronously invokes the four-way asynchronous call to execute the callback method when completion

If the thread that initiates the asynchronous call does not need to process the call result, you can execute the callback method when the call completes. The callback method executes on the ThreadPool thread.

To use a callback method, you must pass the AsyncCallback delegate representing the method to BeginInvoke. You can also pass an object that contains the information that the callback method will use. For example, you can pass a delegate that was used when the call was initiated so that the callback method can call EndInvoke.

  1.  Public classAsyncmain {//asynchronous method puts the thread ID here. Private Static intthreadId; Static voidMain (string[] args) {  //Create An instance of the test class. Asyncdemo AD =NewAsyncdemo (); //Create the delegate. AsyncDelegate dlgt =NewAsyncDelegate (AD.       TestMethod); //Initiate the asychronous call. Include an AsyncCallback//delegate representing the callback method, and the data//needed to call EndInvoke. IAsyncResult ar = dlgt. BeginInvoke ( the,   outThreadId,NewAsyncCallback (Callbackmethod), DLGT); Console.WriteLine ("Press Enter to close application.");  Console.ReadLine (); }   //Callback method must has the same signature as the//AsyncCallback Delegate. Static voidcallbackmethod (IAsyncResult ar) {//Retrieve the delegate. AsyncDelegate dlgt =(asyncdelegate) ar.   asyncstate; //Call EndInvoke to retrieve the results. stringret = dlgt. EndInvoke ( outthreadId, AR); Console.WriteLine ("the call executed on thread {0},WithreturnValue \"{1}\ ".", ThreadId, ret); }  }  

C # Asynchronous invocation of the basic contents of the four methods is introduced to you here, hoping to help you understand and learn C # asynchronous calls.

Reproduced C # asynchronous invocation four-way explanation

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.