0

When an async method is called from a lets say UI thread, if the runtime stumbles upon an await line, it will hand over the awaitable task to a worker thread and release the UI thread. Based on this my question is when an async method has multiple awaits and for ConfigureAwait false or true scenarios, does the runtime switch threads every time it hits an await block? If so wouldn't it cause a lot of thread switching in methods with multiple awaits?

see the code below

static async Task MainAsync()
{
    /* worker thread takes over */
    await awaitable; 

    /* worker thread or the original thread
     * (depending on configure await) 
     * hands execution over to another worker thread? */
    await anotherawaitable;       
}

is this the case?

Cee McSharpface
  • 8,493
  • 3
  • 36
  • 77
trueLife
  • 103
  • 7
  • 1
    they all could be the same thread! – Daniel A. White Jan 17 '19 at 20:30
  • 3
    https://blog.stephencleary.com/2013/11/there-is-no-thread.html – Daniel A. White Jan 17 '19 at 20:30
  • 2
    Asynchrony != Multithreading – CodingYoshi Jan 17 '19 at 20:39
  • Depending on the method and environment it runs in, there may not be a thread at all, there may be a thread pool thread or a new thread or whatever you want. You can write your own task scheduler, set your own synchronization context and make it jump between threads if you want. Or make it run on a single thread. Even if it is scheduled on a thread pool thread, each task can be put on a global of more specific task queue, which is also dependent on parameters of these tasks. There are many combinations. You can even chain them by attaching tasks to task's parent. – FCin Jan 17 '19 at 20:45
  • Calling await doesn't start any thread by the runtime. The choice of whether to start a thread, take a thread from the thread pool, or just wait for an event is completely in the hands of the async method. It can even be implemented by a single line of Thread.Sleep and you caller thread will get blocked. – haimb Jan 20 '19 at 05:46

0 Answers0