. NET asynchronous programming summary ---- code Summary of the four implementation modes,. net ----

Source: Internet
Author: User

. NET asynchronous programming summary ---- code Summary of the four implementation modes,. net ----

Recently, I am very busy. I have to go out to work and take into account my boss's projects. I am busy at the company today. Let's sum up. NET asynchronous call function implementation method, DebugLZQ wrote all the sample code in this article before writing this blog post, did the homework before writing, use the code to speak convincing.

The content of this article aims to use the most concise code to clarify the asynchronous call method. Master laruence in the garden can bypass it. If you do not like it, Do not spray it. If You Are the One, do not disturb it ~

In the previous lz article, I briefly talked about Asynchronization, mainly in terms of understanding. This article mainly describes specific implementation methods. There are four methods to implement asynchronous programming. These four access requests correspond to four asynchronous calling modes, which are divided into two categories: "Waiting" and "Callback. For the four methods, I have made a detailed comment in the code. I am not so embarrassed here. Please use the code to describe them directly.

Method 1: BeginEnvoke EndEnvoke, which belongs to the "Waiting" class.

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; namespace asynchronous call implementation method summary {// <summary> // summary of asynchronous call Methods: // 1. beginEnvoke EndEnvoke // when BeginInvoke is used to call a method asynchronously, if the method is not completed, the EndInvoke method will be blocked all the time, until the called method is executed /// </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 ("the main thread continues to execute... "); // when BeginInvoke is used to call a method asynchronously, The EndInvoke method will be blocked until the called method is executed successfully. endInvoke (result); Console. writeLine ("Press any key to continue... "); Console. readKey (true);} public static void Print (string s) {Console. writeLine ("asynchronous Thread execution started:" + s); Thread. sleep (5000 );}}}

Note that the Code indicates that the program runs as follows:

Method 2: WaitOne. It also belongs to the "Waiting" class.

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; summary of asynchronous call implementation methods of namespace 2 {// <summary> // summary of asynchronous call Methods: // 2. waitOne // you can see that, similar to EndInvoke, EndInvoke is only obtained using the WaitOne function code. /// </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 ("the main thread continues to execute... "); 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 execution started:" + s); Thread. sleep (5000 );}}}

Note that the Code indicates that the program runs as follows:

Method 3: Round Robin. It also belongs to the "Waiting" class.

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; summary of asynchronous call implementation methods of namespace 3 {// <summary> // summary of asynchronous call Methods: // 3. the two methods mentioned earlier in the round-robin process can only wait until the Asynchronous Method is executed. // There is no prompt before the completion, and the whole program is like no response, the user experience is poor. // you can check whether the asynchronous call is complete by checking the IsCompleted attribute of the IasyncResult type. // if not, the prompt information is displayed in a timely manner. // </summary> class Program {public delegate void PrintDelegate (string s); static void Mai N (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 to execute... "); 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 indicates that the program runs as follows:

Method 4: callback. Of course it belongs to the "Callback" class. Recommended !!!!

The preceding three methods can get the execution results after the Asynchronous Method is executed. The main thread is in the waiting state. The biggest difference between callback and callback is that the main thread does not need to wait for the asynchronous thread to finish working when BeginInvoke is called, after the asynchronous thread finishes working, it will take the initiative to call the callback method we provide and handle it in the callback method.

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; summary of asynchronous call implementation methods of namespace 4 {// <summary> // summary of asynchronous call Methods: // 4. callback // the preceding three methods can get the execution result after the Asynchronous Method is executed. The main thread is in the waiting state. /// The biggest difference between callback and callback is that the main thread does not need to wait for the asynchronous thread to finish working when BeginInvoke is called, /// after the asynchronous thread finishes working, it will take the initiative to call the callback method provided by us and perform corresponding processing in the callback method, for example, display the asynchronous call result. /// </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 ("the main thread continues to execute... "); 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 requirement // 1. the return type is void // 2. there is only one parameter IAsyncResult public static void PrintComeplete (IAsyncResult result) {(result. asyncState as PrintDelegate ). endInvoke (result); Console. writeLine ("the current thread ends. "+ result. asyncState. toString ());}}}

Note that the Code indicates that the program runs as follows:

Use the EndInvoke method to obtain the return value of the synchronous function. The above synchronous method returns void. Let's give an example:

using System.Diagnostics;using System.Threading;using System.Windows;namespace TestDelegateWrapper{  /// <summary>  /// Interaction logic for MainWindow.xaml  /// </summary>  public 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 four methods are used to call functions asynchronously. If you have made it clear, write so much ~ I hope it will be helpful for everyone's learning, and I hope you can support the house of helping customers more.

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.