Using asynchronous programming, method calls are run in the background (usually with the help of threads and tasks) and do not block the calling thread.
There are three modes of asynchronous programming: asynchronous mode, event-based asynchronous mode, and task-based asynchronous mode (TAP).
1. Asynchronous mode
Since .NET 1.0, the .NET Framework provides asynchronous features. Many classes (but not all classes) of the .NET Framework implement one or more asynchronous patterns, and custom classes can implement asynchronous patterns through delegate types.
The asynchronous pattern of many classes of the .NET Framework defines the BeginXXX() method and the EndXXX method. For example, the HttpWebRequest class has a synchronous method GetResponse method, and its asynchronous methods are BeginGetResponse and EndGetResponse methods. The BeginXXX() method accepts all input parameters of its synchronization method, and the EndXXX method uses all output parameters of the synchronization method, and returns the result according to the return type of the synchronization method. When using asynchronous mode, the BeginXXX() method also defines an AsyncCallback parameter to accept delegates called after the asynchronous method execution is completed. The BeginXXX() method returns IAsyncResult, used to verify whether the call is completed and wait until the execution of the method is completed.
var client = new HttpWebRequest(); ( ar => { (ar); },null);
Custom classes can implement asynchronous mode through delegate types:
Let's write a synchronization example first:
private void button1_Click(object sender, EventArgs e) { (5000); //("Synchronous completion!"); }
When clicking this button on the form, the thread sleeps for five seconds, and the form cannot be operated within five seconds. Other operations can be performed after five seconds.
Write asynchronous mode:
private void button2_Click(object sender, EventArgs e) { Func<int,string> suncTest = (e1) => { (e1); return "Async mode is done!"; }; (5000,ar => { string re = (ar); (re); }, null); }
Define a delegate and add the method to be executed. Then call the BeginInvoke method for asynchronous execution. The BeginInvoke method can pass parameters of the added method. The first parameter is the parameter of the added method, and the second parameter's type is AsyncCallback. AsyncCallback is a delegate that requires IAsyncResult as a parameter. After executing the asynchronous method, the delegate referenced method will be called. Use the (ar) method to retrieve the results.
The result cannot be returned directly to the UI here, because the UI is bound to a separate thread, and the callback method runs in a background thread. You need to use the Invoke method of the form, which adds items to the collection that will be bound to the UI.
Func<int,string> suncTest = (e1) => { (e1); return "Async mode is done!"; }; string s = (suncTest, 5000).ToString(); = s;
2. Event-based asynchronous mode
In WF and WPF, it is complicated to use asynchronous mode to update the interface. .NET 2.0 introduces an event-based asynchronous mode. In this mode, the event handler is called by a thread with a synchronous context, so it will be easy to update the interface. This pattern is also called asynchronous component pattern.
Similarly, many classes in the .NET Framework provide methods based on event asynchronous patterns, and events-based asynchronous patterns define methods with the suffix of "Async".
var client = new WebClient(); = ; += (sender1, e1) => { string resp = ; var images = (resp); foreach (var image in images) { (image); } }; (new Uri());
For custom classes, you can use the BackgroundWorker class (you can view MSDN) to implement event-based asynchronous mode:
private void button3_Click(object sender, EventArgs e) { string s=""; BackgroundWorker bw = new BackgroundWorker(); += (sender1,e1) => { (5000); s = "Asynchronous completion based on event!"; }; += (sender1, e1) => { = s; }; (); }
Here is a defined event to be called. When the RunWorkerAsync() method is called, the DoWork event is triggered. When the asynchronous method execution is completed, the RunWorkerCompleted event will be triggered, and the added method will be executed.
Here you can directly access the UI elements because the event handler is called from a thread that has a context. In WF and WPF applications, the thread that has a synchronous context is the UI thread.
3. Task-based asynchronous mode (TAP)
Introducing task-based asynchronous mode in .NET 4.5. This is based on the new Task type added in .NET 4.0, and uses the compiler function through the async and await keywords.
Similarly, many classes in the .NET Framework provide methods based on event asynchronous pattern. Event-based asynchronous pattern defines methods with the "Async" suffix and returns a Task type.
Here is a custom task-based asynchronous mode
private async void button4_Click(object sender, EventArgs e) { string re = await AsyncTaskTestAsync(); =re; } Task<string> AsyncTaskTestAsync() { return (() => { (5000); return "Asynchronous completion based on task!"; } ); }
Asynchronous mode specification based on task, it is best to add an Async suffix after the asynchronous method name and return a task. Return to Task<string> here. When calling AsyncTaskTestAsync(), you do not need to declare a Task<string> variable to set the return result of the AsyncTaskTestAsync() method. Just declare a variable of type string and use the await keyword. The await keyword will contact the blocking of the thread (here is the UI thread) and complete other tasks. When the AsyncTaskTestAsync() method is completed, it returns to the UI thread, and the UI thread can obtain the results from the background thread. Then execute the code behind await.
Using the await keyword requires a method of modifying the declaration with async. Until the AsyncTaskTestAsync method is completed, other codes in the method will not continue to be executed, but the thread that starts the button4_Click method can be reused.
async can only be used to return methods that can be used to return Task or void. It cannot be used for the entry of the program, that is, the Main method. await can only be used to return Task methods.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.