Home > Article > Backend Development > C# 5.0 introduces two keywords-async and await
C# 5.0 introduces two keywords async and await. These two keywords help us simplify the implementation code of asynchronous programming to a great extent, and the tasks in TPL have a great relationship with async and await
private async void button1_Click(object sender, EventArgs e) { var length = AccessWebAsync(); // 这里可以做一些不依赖回复的操作 OtherWork(); this.textBox1.Text += String.Format("\n 回复的字节长度为: {0}.\r\n", await length); this.textBox2.Text = Thread.CurrentThread.ManagedThreadId.ToString(); } private async Task<long> AccessWebAsync() { MemoryStream content = new MemoryStream(); // 对MSDN发起一个Web请求 HttpWebRequest webRequest = WebRequest.Create("http://msdn.microsoft.com/zh-cn/") as HttpWebRequest; if (webRequest != null) { // 返回回复结果 using (WebResponse response = await webRequest.GetResponseAsync()) { using (Stream responseStream = response.GetResponseStream()) { await responseStream.CopyToAsync(content); } } } this.textBox3.Text = Thread.CurrentThread.ManagedThreadId.ToString(); return content.Length; } private void OtherWork() { this.textBox1.Text += "\r\n等待服务器回复中.................\n"; }
async is a synchronous execution program, while await plays the role of dividing fragments and suspending the caller. It does not create new threads. According to the analysis of the master:
The first part of the code and the later part of the code where the await keyword appears are executed synchronously (that is, they are executed on the calling thread, which is the GUI thread, so there is no problem of cross-thread access to controls), the key point of await The code snippet is executed on a thread pool thread.
In the above code, methods such as GetResponseAsync encapsulated by FCL are called so as not to block the current UI thread. await does not create a new thread, but as far as here, the await expression does create The new thread - GetResponseAsync does so much that it creates the illusion of superficial synchronization. I have written an article before
C#async and await asynchronous programming study notes
The await keyword is closely related to Task. It can be seen from its specific return value that the deeper await It should be equivalent to the continuewith function of task. Therefore, using the async & await keywords to achieve asynchronous implementation must either call the asynchronous method encapsulated by FCL, or we can call task ourselves to create a new thread to share the tasks of the UI thread to prevent the UI thread. block.
The above is the detailed content of C# 5.0 introduces two keywords-async and await. For more information, please follow other related articles on the PHP Chinese website!