C # 5.0 introduces two keywords async and await, and these two keywords help us to a great extent simplify the implementation code for asynchronous programming, and the task in TPL is very much related to async and await.
Private async void Button1_Click (object sender, EventArgs e) {var length = Accesswebasync (); Here can do some do not rely on the response of the Operation Otherwork (); This.textBox1.Text + = String.Format ("\ n Reply byte length: {0}.\r\n", await length); This.textBox2.Text = Thread.CurrentThread.ManagedThreadId.ToString (); } Private Async Task<long> Accesswebasync () {MemoryStream content = new MemoryStream (); Initiating a Web request to MSDN HttpWebRequest WebRequest = webrequest.create ("http://msdn.microsoft.com/zh-cn/") a s HttpWebRequest; if (webRequest! = null) {//returns the reply result using (WebResponse response = await webreques T.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 waiting for server reply ... \ n"); }
Async is the synchronous execution of the program, and the await is divided into fragments and suspend the role of the caller, and does not create a new thread, according to the Great God Analysis:
The first part of the code that appears in the await keyword and the code that follows it are all synchronous (that is, the GUI thread that executes on the calling thread, so there is no problem with cross-threading access to the control), and the code snippet at the await key is executed on the thread pool threads.
In the above code, such methods as the FCL encapsulated Getresponseasync are called so that the current UI thread is not blocked, and await does not create a new thread, but here the await expression does create a new thread-- What Getresponseasync did. That caused the illusion of surface synchronization. I've written an article before.
C#async and await asynchronous programming learning notes
The await keyword has a great association with a task, and it can be seen from its specific return value that a deeper await is equivalent to the ContinueWith function of the task. So, with Async & The AWAIT keyword implementation asynchronously either calls the FCL encapsulated async method, or we call the task ourselves to create a new thread to share the task of the UI thread to prevent the UI thread from blocking.