The two are very similar. When it encounters an async
method, the C# compiler will generate a state machine, such that the returned Task
represents the completion of your method. Since the only thing that your method does is await another asynchronous operation, then this will be functionally almost equivalent to returning the Task
from the inner asynchronous operation directly.
There is, however, a subtle difference concerning how exceptions from the synchronous part will be thrown. Any logic performed within async
methods, including the synchronous part at the beginning of the method (before the first await
statement), will be compiled as part of the asynchronous operation. This means that precondition exceptions will no longer be delivered synchronously, but asynchronously through the returned Task
:
private static async Task FirstDelayAsync()
{
if (StateNotValid)
throw new NotSupportedException();
await Task.Delay(1000);
}
private static Task SecondDelayAsync()
{
if (StateNotValid)
throw new NotSupportedException();
return Task.Delay(1000);
}
Testing out the above code:
var t1 = FirstDelayAsync();
await t1; // exception thrown here
var t2 = SecondDelayAsync(); // exception thrown here
await t2;
This won't make a difference if you await your asynchronous operation on the same line that you call it. However, it would make a difference if you delay the awaiting; for example, if you launch several asynchronous operations concurrently and then await them together using Task.WhenAll
:
var tasks = Enumerable
.Range(0, 10)
.Select(i => ProcessAsync(i))
.ToArray();
await Task.WhenAll(tasks);
In the above snippet, synchronous exceptions thrown from the ProcessAsync
calls would prevent the subsequent asynchronous operations from even being launched, since the exception immediately stops the enumeration. This is usually preferable for failed preconditions that should stop the entire process.
Update: Another important different is that using await
without ConfigureAwait(false)
will make your code more liable to deadlock. See this answer.