Note that there are some explanatory texts on larger screens.

plurals
  1. POasync/await thread transition curiosity
    primarykey
    data
    text
    <p>I have the following simple console application:</p> <pre class="lang-cs prettyprint-override"><code>class Program { private static int times = 0; static void Main(string[] args) { Console.WriteLine("Start {0}", Thread.CurrentThread.ManagedThreadId); var task = DoSomething(); task.Wait(); Console.WriteLine("End {0}", Thread.CurrentThread.ManagedThreadId); Console.ReadLine(); } static async Task&lt;bool&gt; DoSomething() { times++; if (times &gt;= 3) { return true; } Console.WriteLine("DoSomething-1 sleeping {0}", Thread.CurrentThread.ManagedThreadId); await Task.Run(() =&gt; { Console.WriteLine("DoSomething-1 sleep {0}", Thread.CurrentThread.ManagedThreadId); Task.Yield(); }); Console.WriteLine("DoSomething-1 awake {0}", Thread.CurrentThread.ManagedThreadId); Console.WriteLine("DoSomething-2 sleeping {0}", Thread.CurrentThread.ManagedThreadId); await Task.Run(() =&gt; { Console.WriteLine("DoSomething-2 sleep {0}", Thread.CurrentThread.ManagedThreadId); Task.Yield(); }); Console.WriteLine("DoSomething-2 awake {0}", Thread.CurrentThread.ManagedThreadId); bool b = await DoSomething(); return b; } } </code></pre> <p>with the output</p> <pre><code>Start 1 DoSomething-1 sleeping 1 DoSomething-1 sleep 3 DoSomething-1 awake 4 DoSomething-2 sleeping 4 DoSomething-2 sleep 4 DoSomething-2 awake 4 DoSomething-1 sleeping 4 DoSomething-1 sleep 3 DoSomething-1 awake 3 DoSomething-2 sleeping 3 DoSomething-2 sleep 3 DoSomething-2 awake 3 End 1 </code></pre> <p>I'm aware that console apps don't provide a SynchronizationContext so Tasks run on the thread pool. But what surprises me is that when resuming execution from an await in <code>DoSomething</code>, we are on the same thread as we are on inside the await. I had assumed that we'd either return to the thread we awaited on or be on another thread entirely when we resume execution of the awaiting method.</p> <p>Does anyone know why? Is my example flawed in some way?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload