Multithreading: Interpreting async and await

Source: Internet
Author: User

I accidentally saw the async and await keywords in the morning. It took me a dozen minutes to read the msdn and probably understood what it was. I 'd like to share it with you.

The Chinese word of the await keyword is expected. In our programming, we want to express "I will wait for a value here, but I don't need it now. I will do other things first and tell me when you finish ". In fact, the asynchronous mode is very suitable for real scenarios. In real life, few things are synchronized. When waiting for the car, I had nothing to do. I could use my cell phone to get out and start an email, instead of waiting for the car to come here.

In other words, await can be used in C #5 to help us develop asynchronous programming models. By changing the execution process, asynchronous execution looks more like synchronous execution.

Let me take the code and diagram in msdn as an example.
 

    public partial class MainWindow : Window    {        private async void StartButton_Click(object sender, RoutedEventArgs e)        {            int contentLength = await AccessTheWebAsync();            resultsTextBox.Text +=                String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);        }        async Task<int> AccessTheWebAsync()        {             HttpClient client = new HttpClient();            Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");            DoIndependentWork();            string urlContents = await getStringTask;            return urlContents.Length;        }        void DoIndependentWork()        {            resultsTextBox.Text += "Working . . . . . . .\r\n";        }    }

We can see that it is different from the normal execution process,We will even go back to the "method that seems to have been executed" and then execute it under await.

 

But it is not hard to understand, if you have used yield return. It can be seen that the method can be returned when await is executed. After the action following await is executed, we will return and continue to perform the following steps.

However, the sky is unpredictable, and the experts may never go back. Change the StartButton_Click code to see the following situation.

1         private void StartButton_Click(object sender, RoutedEventArgs e)2         {3             int contentLength = AccessTheWebAsync().Result;4 5             resultsTextBox.Text +=6                 String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);7         }

When we call the Result of a task, this attribute will call the await method internally, that is, it will block the thread, that is, when the thread is executed to 3rd rows, it will be blocked (blocking the thread is a very bad thing to remember ). Wait until the AccessTheWebAsync () method is complete.

But can AccessTheWebAsync () be completed? The answer is no! Because the AccessTheWebAsync method depends on the blocked thread to go back and complete. Okay, a deadlock that waits for each other appears.

 

Your mom calls you home for dinner. Hurry up and execute the code below 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.