今天我们来看一下,同样功能在 Asp.net MVC 4 下的实现,基于.net framework 4.5 下的async支持,让我们的代码更加简单,看下面片断代码名叫Index的Action方法:
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);
Operations translations = new Operations() {
FirstOperation = cnblogsTask.Result, SecondOperation = myblogTask.Result };
return View(translations);
}
private static async Task<string> GetStringAsync(string uri
, CancellationToken cancelToken = default(CancellationToken))
{
using (HttpClient httpClient = new HttpClient())
{
var response = await httpClient.GetAsync(uri, cancelToken);
return (await response.Content.ReadAsStringAsync());
}
}
上面的代码我们实现多个Task并行异步,注意async与await关键字,在.NET 4.5 与 Visual Studio 2012下可用。你只可以使用await关键字同时标注了async的方法。使用异法的HttpClient来替代WebClient类,await关键字运用到HttpClient的异步方法上。使用Task.WhenAll等待所有任务结束。我们知道TPL中还提供了CancellationToken,MVC框架中也提供了AsyncTimeout特性,看面下面示例代码:
[AsyncTimeout(100)]
[HandleError(ExceptionType = typeof(TimeoutException),View = "Error")]
public async Task<ActionResult> IndexCancleAsync()
{
var cancellationToken = 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);
Operations translations = new Operations()
{
FirstOperation = cnblogsTask.Result,
SecondOperation = myblogTask.Result
};
return View(translations);
}
我们设置异步超时为100毫秒,并且我们可以传递CancellationToken的参数给具体的Task。 最后把结果返回给View,实际你可以自行Debug看其中过程。
时间: 2024-10-12 22:04:47