. NET Asynchronous Programming summary----Four types of implementation pattern Code summary

Source: Internet
Author: User
Very busy recently, both go out looking for work and take care of the boss Company's projects. Today in the company, sneak in, summarize. NET in the implementation of the asynchronous call function, Debuglzq write this blog before you write all the sample code of this article, before writing is done homework, with the code to speak persuasive.

The purpose of this article is to use the most concise code to make the method of asynchronous call clear, the Garden Master veteran can bypass, do not like to spray, non-sincere do not disturb ~

LZ's previous article simply said the next asynchronous, mainly from the understanding, this article mainly writes the concrete implementation method. There are 4 ways to implement asynchronous programming, and these 4 kinds of adapting actually correspond to 4 types of asynchronous calls, which are divided into "wait" and "callback" classes. Four methods, I have detailed comments in the code, here is not verbose, directly in the code to explain it

The first method: The Beginenvoke Endenvoke method, which belongs to the "Wait" class.

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading; Namespace asynchronous Call implementation method Summary {  ///<summary>////  1.BeginEnvoke Endenvoke///  When using BeginInvoke to invoke the method asynchronously, if the method is not finished, the EndInvoke method will block until the called method finishes executing///  </summary>  class program  { Public    delegate void Printdelegate (string s);    static void Main (string[] args)    {      printdelegate printdelegate = Print;      Console.WriteLine ("Main thread");       IAsyncResult result= Printdelegate.begininvoke ("Hello World", NULL, NULL);      Console.WriteLine ("Main thread continues execution ...");      When using BeginInvoke to invoke the method asynchronously, if the method is not finished, the EndInvoke method will block until the called method executes      printdelegate.endinvoke (result);       Console.WriteLine ("Press any key to continue ...");      Console.readkey (True);    }     public static void Print (string s)    {      Console.WriteLine ("Asynchronous Thread Begins execution:" +s);      Thread.Sleep ();}}}  

Note that the code has been noted, the program operation results are as follows:

The second method: WaitOne. Also belongs to the "Wait" class.

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading;  Just use the WaitOne function code EndInvoke only.  ///</summary> class Program {public    delegate void Printdelegate (string s);    static void Main (string[] args)    {      printdelegate printdelegate = Print;      Console.WriteLine ("Main thread");      IAsyncResult result = Printdelegate.begininvoke ("Hello World", NULL, NULL);      Console.WriteLine ("Main thread continues execution ...");      Result. Asyncwaithandle.waitone ( -1, false);       Console.WriteLine ("Press any key to continue ...");      Console.readkey (True);    }    public static void Print (string s)    {      Console.WriteLine ("Asynchronous Thread Begins execution:" + s);      Thread.Sleep ();}}}  

Note that the code has been noted, the program operation results are as follows:

The third method: polling. Also belongs to the "Wait" class.

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading; Like no response, the user experience is not good,///////You can check the completion of an asynchronous call by checking the IsCompleted property of the IAsyncResult type, or///if it is not completed, you can display some prompt information//</summary> CLA    SS Program {public delegate void Printdelegate (string s);      static void Main (string[] args) {printdelegate printdelegate = Print;      Console.WriteLine ("Main thread:" +thread.currentthread.managedthreadid);      IAsyncResult result = Printdelegate.begininvoke ("Hello World", NULL, NULL);      Console.WriteLine ("Main thread:" + Thread.CurrentThread.ManagedThreadId + ", continue execution ..."); while (!result.        iscompleted) {Console.WriteLine (".");      Thread.Sleep (500);      } Console.WriteLine ("Main thread:" + Thread.CurrentThread.ManagedThreadId + "Press any key to continue ...");    Console.readkey (TRUE); } public static void Print(String s)      {Console.WriteLine ("Current thread:" + Thread.CurrentThread.ManagedThreadId + s);    Thread.Sleep (5000); }  }}

Note that the code has been noted, the program operation results are as follows:

Fourth method: Callback. Of course it belongs to the "callback" class. Recommended!!!!

The previous three methods were waiting for the asynchronous method to complete before they could get the result of the execution, while the main thread was waiting. The biggest difference is that when calling BeginInvoke, the main thread will not have to wait for the asynchronous thread to finish, and the asynchronous thread will invoke the callback method we provided at the end of the work and handle the callback method accordingly.

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading;  Namespace asynchronous Call implementation Method Summary 4{//<summary>//////4. Callback////Three methods before the execution of the asynchronous method can get the results, the main thread is in the waiting state. The biggest difference is that when calling BeginInvoke, the main thread is not required to wait for the asynchronous thread to finish, and/or the asynchronous thread will invoke the callback method we provided at the end of the work, and handle the callback method accordingly.  For example, displays the result of an asynchronous call.    </summary> class Program {public delegate void Printdelegate (string s);      static void Main (string[] args) {printdelegate printdelegate = Print;      Console.WriteLine ("Main thread.");      Printdelegate.begininvoke ("Hello World", Printcomeplete, printdelegate);       Console.WriteLine ("Main thread continues execution ...");      Console.WriteLine ("Press any key to continue ...");    Console.readkey (TRUE);      public static void Print (String s) {Console.WriteLine ("Current thread:" +s);    Thread.Sleep (5000);      }//callback method requires//1. The return type is void//2. Only one parameter IAsyncResult public static void Printcomeplete (IAsyncResult result) { (result.) AsyncsTate as Printdelegate).      EndInvoke (result); Console.WriteLine ("Current thread ends." + result.)    Asyncstate.tostring ()); }  }}

Note that the code has been noted, the program operation results are as follows:

The return value of the synchronization function is obtained by the EndInvoke method. The previous synchronization method return value is void, and we give an example:

using system.diagnostics;using system.threading;using System.Windows; namespace testdelegatewrapper{//<summary>//Interaction logic for MainWindow.xaml//</summary> Publ    IC Partial class Mainwindow:window {public MainWindow () {InitializeComponent ();       } private void Buttonbase_onclick (object sender, RoutedEventArgs e) {wrappersyncmethodasync ("ABC");    Trace.WriteLine ("Main thread continue ...");         } Private delegate string syncmethod1delegate (String str);      private void Wrappersyncmethodasync (String str) {syncmethod1delegate syncmethod1delegate = SyncMethod1;         Syncmethod1delegate.begininvoke (str, x = = var result= syncmethod1delegate.endinvoke (x);      Using the result to do something trace.writeline (result);    }, NULL);      } private string SyncMethod1 (String str) {Thread.Sleep (2000);    return str; }  }}

The output is as follows:

Main thread Continue ...
Abc

The above is four kinds of implementation of the asynchronous call function of four methods, said very clearly, write so much ~ hope that everyone's learning has helped, but also hope that we support the script of the home PHP Chinese web.

  • Related Article

    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.