我很困惑何时会在方法中使用异步。根据我的测试,这两种方法的工作方式相同。你何时会使用其中一个?
// Returns a task which can be awaited in the controller
private Task<int> RunAsyncTask1()
{
Task<int> task = Task.Run(() =>
{
int result = CalculateMeaningOfLife();
return result;
});
return task;
}
// Returns an actual value - it too, can be awaited in the controller
private async Task<int> RunAsyncTask2()
{
var task = await Task.Run(() => {
int result = CalculateMeaningOfLife();
return result;
});
return task;
}
控制器:
public async Task<ActionResult> Index()
{
Task<int> task = RunAsyncTask1(); // Without await - will continue and not wait for result
int result = await RunAsyncTask1(); // Main Thread put back in Thread Pool, will wait for result
Task<int> task = RunAsyncTask2(); // Without await - will continue and not wait for result
int result = await RunAsyncTask2(); // Main Thread put back in Thread Pool, will wait for result
return View();
}
在方法(RunAsyncTask2())中使用“await”关键字WITHE的唯一好处是,您可以在该方法中设置多个延续吗?