Why is this code different?
The difference is when and where you create the task. There is a big difference between
... Task.Run(async () => await CreateTheTaskInsideTheLambda().ConfigureAwait(false))...
and
var theTask = CreateTheTaskOutsideOfLambda();
... Task.Run(async () => await theTask.ConfigureAwait(false))...
The lambda is executed on the thread pool, so CreateTheTaskInsideTheLambda()
cannot catch any ambient SynchronizationContext. .ConfigureAwait(false)
here changes nothing, it's not necessary.
CreateTheTaskOutsideOfLambda()
on the other hand may catch SynchronizationContext on the first await
inside, if that await
doesn't have .ConfigureAwait(false)
. This may cause a deadlock.
Again .ConfigureAwait(false)
in Task.Run(async () => await theTask.ConfigureAwait(false))
changes nothing.