I have written two articles on asynchronous programming, which can be entered into c#~ asynchronous programming and c#~ asynchronous programming in project use
Each version of. NET has its own master-push technology, like a delegate in. NET1.1, a generic in. NET2.0 in. NET3.0, and Dynimac in the linq,.net4.0 in. The main thing in NET4.5 is asynchronous programming, and the simplest way to implement asynchronous programming is to use the await and async keywords, which are already used in the new. NET Managed class library, and we can use it in the vs2010 add patch and vs2012. In Microsoft's battlefield, we have never seen asynchronous programming so prevalent in the launch. net4.5, so the need for asynchronous methods, are implemented in synchronous and asynchronous two versions, which gives developers a great convenience!
Here are two examples to illustrate how an await and async are used
A remote image is fetched and then responded to on the browser
#regionAsynchronously returns a file stream (increases the throughput capacity of the application) Public AsyncTask<actionresult>Awaitfile () {varresponsehtml =awaitGetResponseStream ("http://static.xuexiba.com/uploadfile/UserInfo/Avatar/201311/1302844759237319155175.jpg"); returnFile (responsehtml,"Image/jpeg"); } Private AsyncTask<stream> GetResponseStream (stringURL) { return awaitgetresponsecontentasync (URL); } Private AsyncTask<stream> Getresponsecontentasync (stringURL) { varHttpClient =NewSystem.Net.Http.HttpClient (); varResponse =awaithttpclient.getasync (URL); if(Response. StatusCode = =System.Net.HttpStatusCode.OK) {return awaitResponse. Content.readasstreamasync (); } Else { return NULL;//Error } } #endregion
Two to get the remote HTML file and then respond on the browser
#regionAsynchronously returns text (increases the throughput capacity of the application) Public AsyncTask<actionresult>awaithtml () {varresponsehtml =awaitGetresponsehtml ("http://www.sina.com"); returnContent (responsehtml); } Private Asynctask<string> getresponsehtml (stringURL) { return awaitgetresponsestringasync (URL); } Private Asynctask<string> Getresponsestringasync (stringURL) { varHttpClient =NewSystem.Net.Http.HttpClient (); varResponse =awaithttpclient.getasync (URL); if(Response. StatusCode = =System.Net.HttpStatusCode.OK) {return awaitResponse. Content.readasstringasync (); } Else { return NULL;//Error } } #endregion
And after the run, we can see that it is normal output, and in its operation behind, we may not know that it is implemented on the main path of the WWW is not run, but asynchronously opened a new thread to do this thing, it is important, it does so for the purpose of only one, that is to engage in high-www response ability, That is, improve the throughput of its programs!
Await&async Application of c#~ asynchronous programming continuation ~.net4.5 main push