DEV Community

Discussion on: .NET Threading Gotchas

Collapse
 
glsolaria profile image
G.L Solaria

The await keyword will by default wait for a task to complete and attempt to join the thread that originally spawned the task.

It is my understanding that ConfigureAwait(true) (the default) does not mean that it will resume on the same thread - just that the continuation will be handled by the same context as the one captured just prior to the call.

Context is a tricky term and I defer to Stephen Cleary for its definition:

This "context" is SynchronizationContext.Current unless it is null, in which case it is TaskScheduler.Current. (If there is no currently-running task, then TaskScheduler.Current is the same as TaskScheduler.Default, the thread pool task scheduler).

It is up to the context to determine if a a new thread will be spun up, an existing thread extracted from a pool, or if the current thread will be reused.

In WPF and WinForms applications using the default (ConfigureAwait(true)) from the UI thread will ensure the continuation resumes on the main UI thread.

In ASP.NET Core and Console applications, the context is the thread-pool task scheduler. This means that if you set ConfigureAwait(true) in a Console application or ASP.NET Core application for example, you are not guaranteed to continue on the same thread because the boolean refers to resuming on the captured context which is not the same thing as a thread.