You can't return the task if the method itself is declared to be async
- so this won't work, for example:
async Task BarAsync()
{
return BazAsync(); // Invalid!
}
That would require a return type of Task<Task>
.
If your method is just doing a small amount of work and then calling just one async method, then your first option is fine, and means there's one fewer task involved. You should be aware that any exceptions thrown within your synchronous method will be delivered synchronously though - indeed, this is how I prefer to handle argument validation.
It's also a common pattern for implementing overloading e.g. by cancellation token.
Just be aware that if you need to change to await something else, you'll need to make it an async method instead. For example:
// Version 1:
Task BarAsync()
{
// No need to gronkle yet...
return BazAsync();
}
// Oops, for version 2 I need to do some more work...
async Task BarAsync()
{
int gronkle = await GronkleAsync();
// Do something with gronkle
// Now we have to await BazAsync as we're now in an async method
await BazAsync();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…