C # asynchronous programming,

Source: Internet
Author: User

C # asynchronous programming,

With asynchronous programming, method calls are run in the background (usually with the help of online processes and tasks) and do not block the call thread.
Asynchronous programming has three modes: asynchronous mode, event-based asynchronous mode, and task-based asynchronous mode (TAP ).
I. asynchronous mode
From. NET 1.0. NET Framework provides the asynchronous feature ,.. NET Framework implements one or more asynchronous modes for many classes (but not all classes). Custom classes can implement asynchronous modes through the delegate type.
The asynchronous mode of many classes in. NET Framework defines the BeginXXX () method and EndXXX method. For example, the HttpWebRequest class has a synchronous method GetResponse. The Asynchronous Method is the BeginGetResponse and EndGetResponse methods. The BeginXXX () method accepts all input parameters of the synchronous method. The EndXXX method uses all output parameters of the synchronous method and returns the result according to the return type of the synchronous method. When the asynchronous mode is used, the BeginXXX () method also defines an AsyncCallback parameter, which is used to accept the delegate called after the Asynchronous Method is executed. The BeginXXX () method returns IAsyncResult to verify whether the call is complete and waits until the execution of the method ends.

  

var client = new HttpWebRequest();        client.BeginGetResponse( ar =>        {            client.EndGetResponse(ar);        },null);

 


The custom class can implement asynchronous mode through the delegate type:
First, write a synchronization example:

  

Private void button#click (object sender, EventArgs e) {Thread. Sleep (5000); // MessageBox. Show ("synchronization completed! ");}

 

 

 

When you click this button on the form, the thread sleeps for five seconds, and the form cannot be operated within five seconds. You can perform other operations after five seconds.
Write asynchronous mode:

  

Private void button2_Click (object sender, EventArgs e) {Func <int, string> suncTest = (e1) =>{ Thread. Sleep (e1); return "asynchronous mode completed! ";}; SuncTest. BeginInvoke (5000, ar =>{ string re = suncTest. EndInvoke (ar); MessageBox. Show (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 the parameters of the add method. The first parameter is the parameter of the added method, and the second parameter type is AsyncCallback. AsyncCallback is a delegate that requires IAsyncResult as the parameter. After the Asynchronous Method is executed, the method referenced by this delegate is called. Use the suncTest. EndInvoke (ar) method to retrieve the result.
The result cannot be directly returned to the UI because the UI is bound to a separate thread, and the callback method runs in a background thread. You need to use the form's Invoke method to add items in the collection bound to the UI.
  

Func <int, string> suncTest = (e1) => {Thread. Sleep (e1); return "asynchronous mode complete! ";}; String s = this. Invoke (suncTest, 5000). ToString (); label1.Text = s;

 

Ii. Event-based asynchronous mode
In WF and WPF, It is very complicated to update the interface in asynchronous mode .. NET 2.0 introduces the event-based asynchronous mode. In this mode, the event handler is called by a thread with a synchronization context, so it is easy to update the interface. This mode is also called the asynchronous component mode.
Similarly, many classes in. NET Framework provide methods based on the event asynchronous mode. The event-based asynchronous mode defines methods with the "Async" suffix.
  

var client = new WebClient();        client.Credentials = req.Credentials;        client.DownloadStringCompleted += (sender1, e1) =>          {            string resp = e1.Result;            var images = req.Parse(resp);            foreach (var image in images)            {              searchInfo.List.Add(image);            }          };        client.DownloadStringAsync(new Uri(req.Url));

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 (); bw. doWork + = (sender1, e1) => {Thread. sleep (5000); s = "Event-based Asynchronous completion! ";}; Bw. RunWorkerCompleted + = (sender1, e1) =>{ label1.Text = s ;}; bw. RunWorkerAsync ();}

 

 

 

An event to be called is defined here. The DoWork event is triggered when the RunWorkerAsync () method is called. After the Asynchronous Method is executed, the RunWorkerCompleted event is triggered and the added method is executed.
You can directly access the UI element here, because the event handler calls it from a thread with a context. In WF and WPF applications, the thread with a synchronization context is the UI thread.

Iii. Task-Based asynchronous mode (TAP)
The task-based asynchronous mode was introduced in. NET 4.5. This type is based on the new Task Type in. NET 4.0 and uses the compiler function through async and await keywords.
Similarly, many classes in. NET Framework provide methods based on the event asynchronous mode. The event-based asynchronous mode defines methods with the "Async" suffix and returns a Task type.
Here we will introduce the custom task-based asynchronous mode.

  

Private async void button4_Click (object sender, EventArgs e) {string re = await AsyncTaskTestAsync (); label1.Text = re;} Task <string> AsyncTaskTestAsync () {return Task. run () => {Thread. sleep (5000); return "Task-based Asynchronous completion! ";});}

 


Specify the asynchronous mode based on the task. It is best to add the Async suffix after the Asynchronous Method Name and return a task. Task <string> is returned. When calling AsyncTaskTestAsync (), you do not need to declare a Task <string> variable to set the returned results of the AsyncTaskTestAsync () method. You only need to declare a variable of the string type and use the await keyword. The await keyword will contact the thread (here is the UI thread) to block and complete other tasks. After the AsyncTaskTestAsync () method is completed, the UI thread is returned, and the UI thread can obtain the result from the background thread. Then run the code after await.
To use the await keyword, you must use async to modify the declaration method. Before the AsyncTaskTestAsync method is completed, other code in the method will not be executed, but the thread that starts the button4_Click method can be reused.
Async can only be used to return a 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 tasks.

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.