Asynchronous call and Asynchronous Design Mode in C # (1)

Source: Internet
Author: User

 

Recently, many asynchronous operations have been used in the project. Here is a summary of "Asynchronous. Most of the summary is from msdn and some of my own experiences.

The usage of "Asynchronous" can be divided into the usage level and the class library design level. The sub-sections are as follows:

1. Call the synchronous method in asynchronous mode (usage level ).

Ii. Use iasyncresult to call the Asynchronous Method (usage level ).

Iii. Asynchronous Design Mode (Design Level) based on iasyncresult ).

4. Event-based asynchronous mode (design level ).

The following describes several aspects of asynchronous programming.

1. Call the synchronous method in asynchronous mode (usage level)

. NET framework allows you to call any method asynchronously. To this end, define the delegate with the same signature as the method you want to call. The Common Language Runtime automatically uses the appropriate signature to define the begininvoke and endinvoke methods for the delegate. The begininvoke method can be used to initiate asynchronous calls. The endinvoke method is used to retrieve the results of asynchronous calls. After begininvoke is called, you can call the endinvoke method at any time. If the asynchronous call is not completed yet, endinvoke will stop the calling thread until the asynchronous call is completed.

This call method uses a delegate for asynchronous calling. Its essence is:Call the begininvoke method. The Common Language Runtime Library (CLR) queues requests and immediately returns them to the caller. This method will be called for threads from the thread pool. The original thread that submits the request freely continues to execute in parallel with the target method, which runs in the thread pool thread.

After an asynchronous call is started, you can perform the following four methods while waiting for the asynchronous call result.

·Perform some operations and call endinvoke until the call is completed.

Using system; using system. threading; namespace examples. advancedprogramming. asynchronousoperations {public class asyncmain {public static void main () {// The Asynchronous Method puts the thread ID here. int threadid; // create an instance of the test class. asyncdemo ad = new asyncdemo (); // create the delegate. asyncmethodcaller caller = new asyncmethodcaller (AD. testmethod); // initiate the asych Invalid us call. iasyncresult result = caller. begininvoke( 3000, out threadid, null, null); thread. sleep (0); console. writeline ("main thread {0} does some work. ", thread. currentthread. managedthreadid); // call this method until the asynchronous operation is completed and the current thread is blocked. String returnvalue = caller. endinvoke (Out threadid, result); console. writeline ("the call executed on thread {0}, with return value \" {1 }\". ", threadid, returnvalue );}}}

 

·And then use iasyncresult .. ::. the asyncwaithandle attribute obtains the waithandle and uses its waitone method (this method can set a time-out period) to stop execution until the waithandle signal is sent and then the endinvoke is called.

Using system; using system. threading; namespace examples. advancedprogramming. asynchronousoperations {public class asyncmain {static void main () {// The Asynchronous Method puts the thread ID here. int threadid; // create an instance of the test class. asyncdemo ad = new asyncdemo (); // create the delegate. asyncmethodcaller caller = new asyncmethodcaller (AD. testmethod); // initiate the Asychronous Call. iasyncresult result = caller. begininvoke( 3000, out threadid, null, null); thread. sleep (0); console. writeline ("main thread {0} does some work. ", thread. currentthread. managedthreadid); // call this method until the asynchronous operation is completed and the current thread is blocked. Result. asyncwaithandle. waitone (); // perform additional processing here. // call endinvoke to retrieve the results. string returnvalue = caller. endinvoke (Out threadid, result); console. writeline ("the call executed on thread {0}, with return value \" {1 }\". ", threadid, returnvalue );}}}

 

·Perform some operations, then round-robin The iasyncresult returned by begininvoke, determine when the asynchronous call is completed, and then call endinvoke.

Using system; using system. threading; namespace examples. advancedprogramming. asynchronousoperations {public class asyncmain {static void main () {// The Asynchronous Method puts the thread ID here. int threadid; // create an instance of the test class. asyncdemo ad = new asyncdemo (); // create the delegate. asyncmethodcaller caller = new asyncmethodcaller (AD. testmethod); // initiate the Asychronous call. iasyncresult result = caller. begininvoke (3000, out threadid, null, null); // wait for the result to return while (result. iscompleted = false) {thread. sleep (10);} // call endinvoke to retrieve the results. string returnvalue = caller. endinvoke (Out threadid, result); console. writeline ("the call executed on thread {0}, with return value \" {1 }\". ", threadid, returnvalue );}}}

 

·Pass the delegate used for the callback method to begininvoke. After the asynchronous call is completed, the method will be executed on the threadpool thread. This callback method calls endinvoke. Note: The callback function is executed in another thread.

 

using System;using System.Threading;namespace Examples.AdvancedProgramming.AsynchronousOperations{    public class AsyncMain     {        // Asynchronous method puts the thread id here.        private static int threadId;        static void Main() {            // Create an instance of the test class.            AsyncDemo ad = new AsyncDemo();            // Create the delegate.            AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);            // Initiate the asychronous call.  Include an AsyncCallback            // delegate representing the callback method, and the data            // needed to call EndInvoke.            IAsyncResult result = caller.BeginInvoke(3000,                out threadId,                 new AsyncCallback(CallbackMethod),                caller );            Console.WriteLine("Press Enter to close application.");            Console.ReadLine();        }        // Callback method must have the same signature as the        // AsyncCallback delegate.        static void CallbackMethod(IAsyncResult ar)         {            // Retrieve the delegate.            AsyncMethodCaller caller = (AsyncMethodCaller) ar.AsyncState;            // Call EndInvoke to retrieve the results.            string returnValue = caller.EndInvoke(out threadId, ar);            Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",                threadId, returnValue);        }    }}

Ii. Use iasyncresult to call the Asynchronous Method (usage level)

. NET Framework supports asynchronous programming in many aspects, including:

· File IO, stream Io, socket Io.

· Network.

· Remote processing channels (HTTP, TCP) and proxies.

· XML Web Services created using ASP. NET.

· ASP. NET web forms.

· Use messagequeue message queues.

These classes or components that have implemented asynchronous operations can directly call their asynchronous methods (starting with begin and end ). For more information about waiting for results after an asynchronous method is called, see "Asynchronous call of synchronous method.

 

Iii. Asynchronous Design Mode Based on iasyncresult (design level)

To be continued...

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.