I have read that async/await methods runs in the same thread as caller and I saw it in a WPF application but while testing a code in console application I see it is running in a
Have I missed something?
Sort of. await
doesn't know anything about threads. It causes the code after the await
keyword (by default) to run in the same SynchronizationContext
as the caller, if it exists.
In the case of a WPF Application, the current SynchronizationContext
is setup to marshal the call back to the UI thread, which means it will end up on the UI thread. (The same is true in Windows Forms). In a Console Application, there is no SynchronizationContext
, so it can't post back onto that context, which means you'll end up on a ThreadPool thread.
If you were to install a custom SynchronizationContext
into SynchronizationContext.Current
, the call would post there. This is not common in Console Applications, however, as it typically requires something like a "message loop" to exist to work properly.