C # Asynchronous Operation Async await

Source: Internet
Author: User

In the process of programming, we encounter many scenarios that require asynchronous operations. For example, to download a file, if the download is done synchronously, then the UI action will be stuck, it is best to be able to download it asynchronously. In C #, it was early to support asynchronous operations, but earlier methods were a bit cumbersome to write. By the time C # 5.0, two keywords were added directly: Async and await, and the support for asynchronous operations was perfect. Let's look at the basic usage of a simple demo for general purpose.

Download a file

Let's take a look at downloading a file in a synchronized way:

private void Btnolddownload_click (object sender, EventArgs e) {    using (WebClient WC = new WebClient ())    {        // We tried to download the Python installation package.        WC. DownloadFile ("Https://www.python.org/ftp/python/3.5.2/python-3.5.2-amd64.exe", "Python.exe");    }    Lbmessage.text = "Download complete. ";}

During the execution of the DownloadFile method, the UI thread is stuck and the application is in an unresponsive state during the entire download process. This is certainly unacceptable, so we should use the following asynchronous way to download the file.

Downloading files asynchronously

Let's take a look at the previous asynchronous code to download the file:

private void Oldasyncdownload_click (object sender, EventArgs e) {    using (WebClient WC = new WebClient ())    {        // We tried to download the Python installation package.        there will be an event notification when the download is complete.        WC. downloadfilecompleted + = wc_downloadfilecompleted;        Wc. DownloadFileAsync (New Uri ("Https://www.python.org/ftp/python/3.5.2/python-3.5.2-amd64.exe"), "Python.exe");}    } private void Wc_downloadfilecompleted (object sender, AsyncCompletedEventArgs e) {    lbmessage.text = "Download complete. ";}

Well, things are a little bit more complicated. A simple download logic has been separated into two methods! Mount the Downloadfilecompleted event in the first method, and then start the download. After the download is complete, notify by Downloadfilecompleted event handler function. If you can get used to this kind of writing, the asynchronous programming interfaces provided by C # earlier are sufficient, because this is exactly how asynchronous operations are implemented.

But, as programmers, we are not satisfied, never ...

Async await mode

The async and await keywords are introduced in C # 5.0, which makes the implementation of asynchronous operations easier and easier!

Private async void Btnmyasync_click (object sender, EventArgs e) {    using (WebClient WC = new WebClient ())    {        //I Try to download the Python installation package.        Task task = WC. Downloadfiletaskasync ("Https://www.python.org/ftp/python/3.5.2/python-3.5.2-amd64.exe", "Python.exe");        You can execute the code here.        await task;    }    Lbmessage.text = "Download complete. ";}

Note the location of the async and await keywords in your code so that the code executes the download logic asynchronously and the UI operation is not blocked during the process. Isn't it amazing?

The biggest magic of this code is that it is almost identical to the code that syncs the downloaded file! Everyone likes to write code that executes sequentially, and the code logic is the clearest. The biggest advantage of async and await is the conversion of code that feels simple to the brain into true asynchronous operation logic.

C # Asynchronous Operation Async await

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.