0

Suppose I have async function with the following code.

var reply = await httpClient.GetAsync(somePath);
ProcessReply(reply);

The async function with this code is called in main thread of WPF application. When I execute it ProcessReply always runs asynchronously from dispatcher in main thread, for example if I block main thread continuation is not reached. What controls which thread runs the code after await? Is it guaranteed or possible to make it guaranteed that part after await runs in main thread?

Muxecoid
  • 1,193
  • 1
  • 9
  • 22
  • I think by default it will, you can use the configureawaiter method to change this behavior. – Mansoor Jan 31 '21 at 17:27
  • Threads and Tasks have nothing to do with each other: https://stackoverflow.com/questions/4130194/what-is-the-difference-between-task-and-thread. You can run code asynchronously without ever using a second thread. – MakePeaceGreatAgain Jan 31 '21 at 17:27
  • 5
    _"What controls which thread runs the code after await?"_ It is controlled by the synchronization context. If `SynchronizationContext.Current` is not null on the current thread, then an `await` call is guaranteed to be continued on the original thread, unless you explicitly allow the continuation on any thread by eg. `await httpClient.GetAsync(somePath).ConfigureAwait(false)` – György Kőszeg Jan 31 '21 at 17:34
  • 1
    @GyörgyKőszeg A better way of saying it is: it's guaranteed *not* to run on a different thread. If there is no message pump on that thread for example, then it may never run. – Charlieface Jan 31 '21 at 17:46
  • 1
    @HimBromBeere: Threads and Tasks are obviously related; otherwise, `Task` wasn't defined in the `System.Threading` namespace in the first place. Of course, it is often assumed that every task must have some dedicated thread somewhere, which not true [as we learned it](https://blog.stephencleary.com/2013/11/there-is-no-thread.html). But saying they have nothing to do with each other is just the other extreme. – György Kőszeg Jan 31 '21 at 17:54
  • @Muxecoid: I recommend reading [my async intro](https://blog.stephencleary.com/2012/02/async-and-await.html). – Stephen Cleary Feb 01 '21 at 01:16
  • @GyörgyKőszeg You wrote: _"If `SynchronizationContext.Current` is not null on the current thread, then an `await` call is guaranteed to be continued on the original thread..."_ While this is often the case (e.g. WinForms, WPF...), this is not necessarily true! The continuation thread depends on the implementation of the concrete `SynchronizationContext`. The context can also decide to continue on a `ThreadPool` thread or anywhere else. See [this SO answer](https://stackoverflow.com/a/18098557/273527) for more details. – gehho Oct 14 '22 at 16:02

0 Answers0