Is there any scenario where writing method like this:
public async Task DoSomethingAsync()
{
// Some synchronous code
There is one sneaky case when return
in normal method and return await
in async
method behave differently: when combined with using
(or, more generally, any return await
in a try
block).
Consider these two versions of a method:
Task DoSomethingAsync()
{
using (var foo = new Foo())
{
return foo.DoAnotherThingAsync();
}
}
async Task DoSomethingAsync()
{
using (var foo = new Foo())
{
return await foo.DoAnotherThingAsync();
}
}
The first method will Dispose()
the Foo
object as soon as the DoAnotherThingAsync()
method returns, which is likely long before it actually completes. This means the first version is probably buggy (because Foo
is disposed too soon), while the second version will work fine.