更新时间:2022-06-06 09:01:08
有一个鬼鬼祟祟的情况下,当返回
在正常的方法和返回计谋
在异步
方法不同的表现:在使用(或者更一般地说,任何与
返回待机
在尝试
块)。
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();
}
}
第一种方法是将的Dispose()
的富
对象一旦 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.