I'm confused when to one would use async inside a method. Based on my tests both of these methods work the same way. When would you use one vs. other?
// 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;
}
Controller:
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();
}
Is the only benefit of having "await" keyword WITHIN a method (RunAsyncTask2()) so that you can set up multiple continuations within that method?