The Task object is an object like any other if you take away the async-await keywords.
Consider this example:
public async Task DoStuffAsync()
{
await WaitAsync();
await WaitDirectlyAsync();
}
private async Task WaitAsync()
{
await Task.Delay(1000);
}
private Task WaitDirectlyAsync()
{
return Task.Delay(1000);
}
The difference between this two methods is simple:
WaitAsync wait for Task.Delay to finish, and then returns.WaitDirectlyAsync does not wait, and just returns the Task object instantly.Every time you use the await keyword, the compiler generates code to deal with it (and the Task object it awaits).
await WaitAsync() this happens twice: once in the calling method, and once in the method itself.await WaitDirectlyAsync this happens only once (in the calling method). You would therefore archive a little speedup compared with await WaitAsync().Careful with exceptions: Exceptions will bubble up the first time a Task is awaited. Example:
private async Task WaitAsync()
{
try
{
await Task.Delay(1000);
}
catch (Exception ex)
{
//this might execute
throw;
}
}
private Task WaitDirectlyAsync()
{
try
{
return Task.Delay(1000);
}
catch (Exception ex)
{
//this code will never execute!
throw;
}
}