Home > Article > Backend Development > Summary of .NET asynchronous programming----Code summary of four implementation modes
I have been very busy recently. I have to go out to find a job and also take care of the projects of my boss's company. Today at the company, I took a break from my busy schedule to summarize the implementation method of asynchronous calling functions in .NET. Before writing this blog post, DebugLZQ wrote all the sample codes in this article. I did my homework before starting to write, so I can speak in code. persuasive.
The purpose of this article is to use the most concise code to explain the asynchronous calling method clearly. Experts in the garden can avoid it. If you don’t like it, don’t complain. If you are the one, don’t disturb~
lz’s previous article simply said it Next, asynchronous is mainly from the perspective of understanding; this article mainly writes about specific implementation methods. There are 4 methods to choose from to implement asynchronous programming. These 4 types of requests actually correspond to 4 asynchronous calling modes, which are divided into two categories: "wait" and "callback". I have made detailed comments in the code for the four methods. I won’t go into too much detail here. Let’s just use the code to explain. The first method: 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 异步调用实现方法汇总 { /// <summary> /// 异步调用方法总结: /// 1.BeginEnvoke EndEnvoke /// 当使用BeginInvoke异步调用方法时,如果方法未执行完,EndInvoke方法就会一直阻塞,直到被调用的方法执行完毕 /// </summary> class Program { public delegate void PrintDelegate(string s); static void Main(string[] args) { PrintDelegate printDelegate = Print; Console.WriteLine("主线程"); IAsyncResult result= printDelegate.BeginInvoke("Hello World.", null, null); Console.WriteLine("主线程继续执行..."); //当使用BeginInvoke异步调用方法时,如果方法未执行完,EndInvoke方法就会一直阻塞,直到被调用的方法执行完毕 printDelegate.EndInvoke(result); Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); } public static void Print(string s) { Console.WriteLine("异步线程开始执行:"+s); Thread.Sleep(5000); } } }
Things that need attention are noted in the code. The results of the program are as follows:
Second method: WaitOne. Also belongs to the "waiting" category.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace 异步调用实现方法汇总2 { /// <summary> /// 异步调用方法总结: /// 2.WaitOne /// 可以看到,与EndInvoke类似,只是用WaitOne函数代码了EndInvoke而已。 /// </summary> class Program { public delegate void PrintDelegate(string s); static void Main(string[] args) { PrintDelegate printDelegate = Print; Console.WriteLine("主线程"); IAsyncResult result = printDelegate.BeginInvoke("Hello World.", null, null); Console.WriteLine("主线程继续执行..."); result.AsyncWaitHandle.WaitOne(-1, false); Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); } public static void Print(string s) { Console.WriteLine("异步线程开始执行:" + s); Thread.Sleep(5000); } } }
Things that need attention are noted in the code. The program running results are as follows:
The third method: polling. It also belongs to the "waiting" category.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace 异步调用实现方法汇总3 { /// <summary> /// 异步调用方法总结: /// 3.轮询 /// 之前提到的两种方法,只能等下异步方法执行完毕, /// 在完毕之前没有任何提示信息,整个程序就像没有响应一样,用户体验不好, /// 可以通过检查IasyncResult类型的IsCompleted属性来检查异步调用是否完成, /// 如果没有完成,则可以适时地显示一些提示信息 /// </summary> class Program { public delegate void PrintDelegate(string s); static void Main(string[] args) { PrintDelegate printDelegate = Print; Console.WriteLine("主线程:"+Thread.CurrentThread.ManagedThreadId ); IAsyncResult result = printDelegate.BeginInvoke("Hello world.", null, null); Console.WriteLine("主线程:" + Thread.CurrentThread.ManagedThreadId + ",继续执行..."); while (!result.IsCompleted) { Console.WriteLine("."); Thread.Sleep(500); } Console.WriteLine("主线程:" + Thread.CurrentThread.ManagedThreadId + " Press any key to continue..."); Console.ReadKey(true); } public static void Print(string s) { Console.WriteLine("当前线程:" + Thread.CurrentThread.ManagedThreadId + s); Thread.Sleep(5000); } } }
Things that need attention are noted in the code. The program running results are as follows:
The fourth method: callback. Definitely falls into the "callback" category. recommend! ! ! !
The previous three methods can only get the execution results after waiting for the asynchronous method to complete, during which the main thread is in a waiting state. The biggest difference between callbacks and them is that as long as the callback method is provided when calling BeginInvoke, then the main thread does not need to wait for the asynchronous thread to complete its work. The asynchronous thread will actively call the callback method we provided after the work is completed, and in the callback method Do the appropriate processing.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace 异步调用实现方法汇总4 { /// <summary> /// 异步调用方法总结: /// 4.回调 /// 之前三种方法者在等待异步方法执行完毕后才能拿到执行的结果,期间主线程均处于等待状态。 /// 回调和它们最大的区别是,在调用BeginInvoke时只要提供了回调方法,那么主线程就不必要再等待异步线程工作完毕, /// 异步线程在工作结束后会主动调用我们提供的回调方法,并在回调方法中做相应的处理,例如显示异步调用的结果。 /// </summary> class Program { public delegate void PrintDelegate(string s); static void Main(string[] args) { PrintDelegate printDelegate = Print; Console.WriteLine("主线程."); printDelegate.BeginInvoke("Hello world.", PrintComeplete, printDelegate); Console.WriteLine("主线程继续执行..."); Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); } public static void Print(string s) { Console.WriteLine("当前线程:"+s); Thread.Sleep(5000); } //回调方法要求 //1.返回类型为void //2.只有一个参数IAsyncResult public static void PrintComeplete(IAsyncResult result) { (result.AsyncState as PrintDelegate).EndInvoke(result); Console.WriteLine("当前线程结束." + result.AsyncState.ToString()); } } }
Things that need attention are noted in the code. The program running results are as follows:
Get the return value of the synchronization function through the EndInvoke method. The return value of the above synchronous method is 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 are the four methods of asynchronous calling functions, which are very clear. , that’s all~ I hope it will be helpful to everyone’s study, and I also hope that everyone will support the Script Home php Chinese website.