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<SomeResult> DoSomethingAsync()
{
using (var foo = new Foo())
{
return foo.DoAnotherThingAsync();
}
}
async Task<SomeResult> 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…