C # basic & mdash; talk about the evolution history of. NET asynchronous programming

Source: Internet
Author: User

The most important improvement of C #5.0 is to provide more powerful asynchronous programming. C #5.0 adds only two new keywords: async and await, which will be highlighted later.

In asynchronous programming, method calls are run in the background (usually with the help of a thread or task) and do not block the call thread.

This article describes three asynchronous programming modes: asynchronous mode, event-based asynchronous mode, and the newly added Task-Based asynchronous programming mode (TAP ). TAP is implemented using the async and await keywords. Through the comparison here, we will realize the real advantages of the new Task-Based asynchronous mode.

Suppose that we need to perform a time-consuming operation (Here we use the webclient object to download the Baidu homepage code), and then implement it through synchronization and the three asynchronous modes mentioned above.

Create a console application:

  Main(= = resp = client.DownloadString(

Run the above Code. When DownloadString is executed, the main thread will be blocked. If there is a user interface, the user experience will be poor, and the speed of DownloadString method depends on the network speed and other reasons, in this case, it is necessary to use Asynchronous calls.

Implement Asynchronous mode to define the BeginXXX method and EndXXX method. For example, if there is a synchronous method DownloadString, the asynchronous method will be converted into two methods: BeginDownloadString and EndDownloadString. The inxxx Asynchronous Method accepts all input parameters of the synchronous method and an AsyncCallback parameter (a delegate that is called after the Asynchronous Method is executed), and returns an IAsyncResult object to verify whether the call is complete, the EndXXX Asynchronous Method uses all the output parameters of the synchronous method and returns the result based on the return type of the synchronous method (in simple words, the return value of the asynchronous execution method is obtained, if the asynchronous method is not completed, the main thread is blocked until the Asynchronous Method execution ends ).

WebClient does not implement asynchronous mode, but can be replaced by the HttpWebRequest class (This class includes BeginGetResponse and EndGetResponse ):

  Main(= (HttpWebRequest)WebRequest.Create(=>=            }, 

If you have to use WebClient to implement asynchronous mode, you need to use a delegate (only to the code is not described ):

  Main(            Func<, > downloadString = url =>= =            downloadString.BeginInvoke(, ar => resp =

The advantage of asynchronous mode is that you can implement asynchronous programming using delegation. You do not need to change the program behavior. It does not block interface operations. However, the process of using the asynchronous mode is very complex (especially when Windows form or wpf involves interface update operations ). Fortunately,. NET2.0 launched the event-based asynchronous mode, which allows you to easily update the interface.

The event-based asynchronous mode defines a method with the "Async" suffix. For example, for the synchronous method DownloadString, The WebClient class provides an asynchronous Variant Method DownloadStringAsync. After an Asynchronous Method is completed, it does not define the called deleGATE, but defines the event. After the Asynchronous Method DownloadStringAsync is complete, the DownloadStringCompleted event is called directly. The implementation method is similar to the above. However, you can directly access the UI elements.

Here we change to a winform project (the interface only contains one label and one button), click the button to update the label value:

  button1_Click(= =+= (sender1, e1) => resp == resp.Substring( Uri(

The advantage of event-based asynchronous mode is that it is easy to use. However, it is not that easy to implement this mode in a custom class. There are still some methods. You can use the BackgroundWorker class to call the synchronous method asynchronously. The BackgroundWorker class implements the event-based asynchronous mode. Also, this mode is out of order compared with synchronous method calls. Before calling an Asynchronous Method, You need to define what happens when the method is completed. Therefore, we will enter the new world of asynchronous programming and use async and await keywords.

Check the code first this time:

    button1_Click(= = resp= client.DownloadStringTaskAsync(= resp.Substring(

In. NET4.5, The WebClient class is updated and the task-based asynchronous mode is provided. This mode defines a method with the suffix "Async" and returns a Task type. Because the WebClient class already provides a method with the "Async" suffix, the new method is called DownloadStringTaskAsync.

The DownloadStringTaskAsync method declaration returns the Task <string> type. However, you do not need to declare a variable of the Task <string> type for the result returned by the DownloadStringTaskAsync method. You only need to declare a variable of the string type and use the await keyword. The await keyword does not block the thread that completes other tasks. After the DownloadStringTaskAsync method completes background processing, the UI thread continues and obtains the result from the background thread and assigns it to resp. At the same time, the next line of code with the await keyword will continue to be executed.

Now the code is much simpler. There is no blocking, and you do not need to manually switch back to the UI thread. These are automatically implemented. The code sequence is basically the same as the conventional Synchronous Programming.

Not all. NET FrameWork classes introduce new asynchronous methods in. NET 4.5. Some classes still only provide asynchronous modes of BeginXXX and EndXXX methods. What should I do?

The HttpWebResponse we used above is used as an example (assuming there is no new Asynchronous Method): the generic parameter Task <WebResponse> Of The Task Type defines the return value type of the call method, the first two parameters of the FromAsync method are the delegate type, and the corresponding BeginXXX and EndXXX are passed in. Because we have not entered any parameters, the object status of the parameters is not input. All parameters are null. The Code is as follows:

     button1_Click(= (HttpWebRequest)WebRequest.Create(= (HttpWebResponse) Task<WebResponse>.Factory.FromAsync(req.BeginGetResponse, req.EndGetResponse, 

 

I have always been vague about this. Now I have learned a lot about asynchronous programming and multithreading, which is also very complicated. This article will briefly introduce this.

I think it's better to say "like ".

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.