This question already has an answer here:
In my understanding, if I await an async function, then the following code will be wrapped in a delegate and executed after the async function returns:
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;
}
It sounds like equal to if I explicitly wrap following code in a ContinueWith:
async bool Test()
{
bool res = await ReadAsync(...)
.ContinueWith(t =>
{
byte[] arr = t.Result;
if (arr != null)
{
// Do something
return true;
}
return false;
});
}
Are there any differences between these two implementations?
One mayor difference is that if the thread you call await
from has a SynchronizationContext
, await
will schedule the continuation inside that SynchronizationContext
by default. So after the await you will be back on the same thread as before. You can change that by using .ConfigureAwait(false)
.
With .ContinueWith()
it is eaxactly the other way around, by default it will be scheduled on an aribitary (threadpool) thread unless you pass TaskScheduler.FromCurrentSynchronizationContext()
to it.
.Wait()
in the.ContinueWith()
example. This is the actual mayor difference as the answer explains. - bitbonk