Task
. NET 4.0 brings us the task async, and we have the following three ways to create a task.
1,task.factory.startnew, more commonly used.
2,task.run, which is added in. NET 4.5.
3,task.fromresult, if the result is calculated, you can use this method to create the task.
The following is a continuation of Task.Factory.StartNew to achieve the previous example, the code is as follows.
1 // <summary>2 /// use Task,task.factory.startnew to create a new thread3 // </summary>4 /// <param name= "Sender" ></param>5 /// <param name= "E" ></param>6 Private voidButton4_Click (Objectsender, EventArgs e)7{8 This. richTextBox1.Text = "Processing Request ...";9 TenTask.Factory.StartNew (() = One{ A //The code below can be encapsulated, a method that does not return a value -var url = This. TextBox1.Text.Trim (); -var request = httpwebrequest.create (URL); thevar response = Request. GetResponse (); -var stream = Response. GetResponseStream (); - using(StreamReader reader =NewStreamReader (Stream)) -{ +var content = reader. ReadToEnd (); - This. richTextBox1.Text = content; +} A}); at}
View Code
Tasks are easier to use than threadpool thread pools, and they support interactive operations such as thread cancellation, completion, and failure notification, which ThreadPool does not have. And the task can have a return value.
Async/await
Async&await is a new feature of. NET 4.5,
The following is an example of using async&await to implement it again, as shown in the code below.
1 // <summary>2 // Use async/await3 // </summary>4 /// <param name= "Sender" ></param>5 /// <param name= "E" ></param>6 PrivateAsyncvoidButton5_click (Objectsender, EventArgs e)7{8 This. richTextBox1.Text = "Processing Request ...";9 Tenawait Doworkasync (); One} A - PublicAsync Task Doworkasync () -{ thevar url = This. TextBox1.Text.Trim (); -var request = httpwebrequest.create (URL); -var response = Request. GetResponse (); -var stream = Response. GetResponseStream (); + using(StreamReader reader =NewStreamReader (Stream)) -{ +var content = reader. ReadToEnd (); A This. richTextBox1.Text = content; at} -}
View Code
Have the following questions:
1, do you seem to be using async,ui threads or blocking?
2, using async does not create a new thread?
Task-based Asynchronous mode (TAP)