Today, let's take a look at the implementation of the same functionality under ASP. NET MVC 4, which is based on async support under the. NET Framework 4.5, to make our code simpler, see the following fragment code called Index's action method:
Public async task<actionresult> Indexasync ()
{
var cnblogstask = Getstringasync ("http://www.cnblogs.com");
var myblogtask = Getstringasync ("Http://www.cnblogs.com/wintersun");
Asynchronously wait for them all to complete.
Await Task.whenall (Cnblogstask, Myblogtask);
Firstoperation = Cnblogstask.result, secondoperation = Myblogtask.result};
Return View (translations);
}
Static async task<string> getstringasync (string URI
Default (CancellationToken))
{
New HttpClient ())
{
var response = await Httpclient.getasync (URI, Canceltoken);
Return (await response. Content.readasstringasync ());
}
}
The above code allows us to implement multiple tasks in parallel asynchronously, noting the async and await keywords, available under. NET 4.5 with Visual Studio 2012. You can only use the await keyword to annotate the Async method at the same time. Instead of the WebClient class, the await keyword is applied to the HttpClient async method, using the httpclient of the Xor method. Use Task.whenall to wait for all tasks to end. We know that TPL also provides the AsyncTimeout feature in the CANCELLATIONTOKEN,MVC framework, looking at the following example code:
[AsyncTimeout (100)]
"Error")]
Public async task<actionresult> Indexcancleasync ()
{
New CancellationToken (false);
var cnblogstask = Getstringasync ("http://www.cnblogs.com", CancellationToken);
var myblogtask = Getstringasync ("Http://www.cnblogs.com/wintersun", CancellationToken);
Await Task.whenall (Cnblogstask, Myblogtask);
New Operations ()
{
Firstoperation = Cnblogstask.result,
Secondoperation = Myblogtask.result
};
Return View (translations);
}
We set the asynchronous timeout to 100 milliseconds, and we can pass CancellationToken parameters to the specific task. Finally, the results are returned to view, and you can actually debug the process yourself.
ASP. NET MVC 4 Async method