根据我的理解,如果我等待一个异步函数,那么下面的代码将被包装在一个委托中,并在异步函数返回后执行:
async bool Test()
{
await byte[] arr = ReadAsync(....)
// all following code will be wrapped into a delegate
if (arr != null)
{
// Do something
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
如果我将以下代码显式包装在 ContinueWith 中,这听起来等于:
async bool Test()
{
bool res = await ReadAsync(...)
.ContinueWith(t =>
{
byte[] arr = t.Result;
if (arr != null)
{
// Do something
return true;
}
return false;
});
}
Run Code Online (Sandbox Code Playgroud)
这两种实现之间有什么区别吗?
一个主要区别是,如果您调用的线程await具有SynchronizationContext,await将SynchronizationContext默认安排在该线程内的延续。因此,在等待之后,您将回到与以前相同的线程上。您可以使用.ConfigureAwait(false).
有了.ContinueWith()它eaxactly周围的其他方式,默认情况下它可能是在一个aribitary(线程池)线,除非你计划传递TaskScheduler.FromCurrentSynchronizationContext()给它。