public async Task<string> GetNameAndContent()
{
var nameTask = GetLongRunningName(); //这个方法是异步的
var content = GetContent(); //这个方法是同步的
var name = await nameTask;
return name + ": " + content;
}
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
Stopwatch watch = new Stopwatch();
watch.Start();
ContentManagement service = new ContentManagement();
var content = service.GetContent();
var count = service.GetCount();
var name = service.GetName();
watch.Stop();
ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;
return View();
}
[HttpGet]
public async Task<ActionResult> IndexAsync()
{
Stopwatch watch = new Stopwatch();
watch.Start();
ContentManagement service = new ContentManagement();
var contentTask = service.GetContentAsync();
var countTask = service.GetCountAsync();
var nameTask = service.GetNameAsync();
var content = await contentTask;
var count = await countTask;
var name = await nameTask;
watch.Stop();
ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;
return View("Index");
}
}
void:如果一个异步方法返回void,它不能被等待。这实际上把方法变成了“fire and forget(阅后即焚)”方法,这样的情况很少出现。进一步,返回void的异步方法的错误处理有点不同,比如shown by Stephen Cleary。没有理由使用void作为异步调用的返回类型,除非完全不关心调用是否实际完成。
请发表评论