async/await different thread ID

Solution 1:

I recommend you read my async intro post for an understanding of the async and await keywords. In particular, await (by default) will capture a "context" and use that context to resume its asynchronous method. This "context" is the current SynchronizationContext (or TaskScheduler, if there is no SynchronzationContext).

I want to know where does the asynchronously part run, if there are no other threads created? If it runs on the same thread, shouldn't it block it due to long I/O request, or compiler is smart enough to move that action to another thread if it takes too long, and a new thread is used after all?

As I explain on my blog, truly asynchronous operations do not "run" anywhere. In this particular case (Task.Delay(1)), the asynchronous operation is based off a timer, not a thread blocked somewhere doing a Thread.Sleep. Most I/O is done the same way. HttpClient.GetAsync for example, is based off overlapped (asynchronous) I/O, not a thread blocked somewhere waiting for the HTTP download to complete.


Once you understand how await uses its context, walking through the original code is easier:

static void Main(string[] args)
{
  Console.WriteLine("Main: " + Thread.CurrentThread.ManagedThreadId);
  MainAsync(args).Wait(); // Note: This is the same as "var task = MainAsync(args); task.Wait();"
  Console.WriteLine("Main End: " + Thread.CurrentThread.ManagedThreadId);

  Console.ReadKey();
}

static async Task MainAsync(string[] args)
{
  Console.WriteLine("Main Async: " + Thread.CurrentThread.ManagedThreadId);
  await thisIsAsync(); // Note: This is the same as "var task = thisIsAsync(); await task;"
}

private static async Task thisIsAsync()
{
  Console.WriteLine("thisIsAsyncStart: " + Thread.CurrentThread.ManagedThreadId);
  await Task.Delay(1); // Note: This is the same as "var task = Task.Delay(1); await task;"
  Console.WriteLine("thisIsAsyncEnd: " + Thread.CurrentThread.ManagedThreadId);
}
  1. The main thread starts executing Main and calls MainAsync.
  2. The main thread is executing MainAsync and calls thisIsAsync.
  3. The main thread is executing thisIsAsync and calls Task.Delay.
  4. Task.Delay does its thing - starting a timer and whatnot - and returns an incomplete task (note that Task.Delay(0) would return a completed task, which alters the behavior).
  5. The main thread returns to thisIsAsync and awaits the task returned from Task.Delay. Since the task is incomplete, it returns an incomplete task from thisIsAsync.
  6. The main thread returns to MainAsync and awaits the task returned from thisIsAsync. Since the task is incomplete, it returns an incomplete task from MainAsync.
  7. The main thread returns to Main and calls Wait on the task returned from MainAsync. This will block the main thread until MainAsync completes.
  8. When the timer set by Task.Delay goes off, thisIsAsync will continue executing. Since there is no SynchronizationContext or TaskScheduler captured by that await, it resumes executing on a thread pool thread.
  9. The thread pool thread reaches the end of thisIsAsync, which completes its task.
  10. MainAsync continues executing. Since there is no context captured by that await, it resumes executing on a thread pool thread (actually the same thread that was running thisIsAsync).
  11. The thread pool thread reaches the end of MainAsync, which completes its task.
  12. The main thread returns from its call to Wait and continues executing the Main method. The thread pool thread used to continue thisIsAsync and MainAsync is no longer needed and returns to the thread pool.

The important takeaway here is that the thread pool is used because there's no context. It is not automagically used "when necessary". If you were to run the same MainAsync/thisIsAsync code inside a GUI application, then you would see very different thread usage: UI threads have a SynchronizationContext that schedules continuations back onto the UI thread, so all the methods will resume on that same UI thread.

Solution 2:

I wondered exactly the same. For me the explanations by MSDN were contradictory:

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread.

MSDN: Asynchronous Programming with async and await

An await expression does not block the thread on which it is executing. [..] When the task completes, it invokes its continuation, and execution of the async method resumes where it left off.

await (C#-Referenz)

I didn't understand how the original thread could be not blocked, without the use of additional threads. Additionally the "invoke" wording suggested that there are multiple threads used somewhere and somehow.

But then I realized, that everything is written correctly, that there aren't used any other threads by these keywords. It is by design of the Task class to provide mechanisms that may use different threads - or not.

While stephen-cleary beautifully explained these mechanisms for the Task.Delay() method, I extended the MSDN example to learn how await behaves with Task.Run():

private async void ds_StartButton_Click(object sender, EventArgs e)
{
    textBox1.AppendText(DateTime.Now.ToString() + " [" + Thread.CurrentThread.ManagedThreadId + "] Started MSDN Example ..." + Environment.NewLine);

    // Call the method that runs asynchronously.
    string result = await WaitAsynchronouslyAsync();

    // Call the method that runs synchronously.
    //string result = await WaitSynchronously ();

    // Do other Schdaff
    textBox1.AppendText(DateTime.Now.ToString() + " [" + Thread.CurrentThread.ManagedThreadId + "] Foobar #1 ..." + Environment.NewLine);
    textBox1.AppendText(DateTime.Now.ToString() + " [" + Thread.CurrentThread.ManagedThreadId + "] Foobar #2 ..." + Environment.NewLine);
    textBox1.AppendText(DateTime.Now.ToString() + " [" + Thread.CurrentThread.ManagedThreadId + "] Foobar #3 ..." + Environment.NewLine);
    textBox1.AppendText(DateTime.Now.ToString() + " [" + Thread.CurrentThread.ManagedThreadId + "] Foobar #4 ..." + Environment.NewLine);
    textBox1.AppendText(DateTime.Now.ToString() + " [" + Thread.CurrentThread.ManagedThreadId + "] Foobar #5 ..." + Environment.NewLine);
    textBox1.AppendText(DateTime.Now.ToString() + " [" + Thread.CurrentThread.ManagedThreadId + "] Foobar #6 ..." + Environment.NewLine);
    textBox1.AppendText(DateTime.Now.ToString() + " [" + Thread.CurrentThread.ManagedThreadId + "] Foobar #7 ..." + Environment.NewLine);

    // Display the result.
    textBox1.Text += result;
}

// The following method runs asynchronously. The UI thread is not
// blocked during the delay. You can move or resize the Form1 window 
// while Task.Delay is running.
public async Task<string> WaitAsynchronouslyAsync()
{
    Console.WriteLine(DateTime.Now.ToString() + " [" + Thread.CurrentThread.ManagedThreadId + "] Entered WaitAsynchronouslyAsync()");
    await Task.Delay(10000);
    Console.WriteLine(DateTime.Now.ToString() + " [" + Thread.CurrentThread.ManagedThreadId + "] Task.Delay done, starting random string generation now ...");

    await Task.Run(() => LongComputation());

    Console.WriteLine(DateTime.Now.ToString() + " [" + Thread.CurrentThread.ManagedThreadId + "] Leaving WaitAsynchronouslyAsync() ...");
    return DateTime.Now.ToString() + " [" + Thread.CurrentThread.ManagedThreadId + "] Finished MSDN Example." + Environment.NewLine;
}

// The following method runs synchronously, despite the use of async.
// You cannot move or resize the Form1 window while Thread.Sleep
// is running because the UI thread is blocked.
public async Task<string> WaitSynchronously()
{
    // Add a using directive for System.Threading.
    Thread.Sleep(10000);
    return DateTime.Now.ToString() + " [" + Thread.CurrentThread.ManagedThreadId + "] Finished MSDN Bad Ass Example." + Environment.NewLine;
}

private void ds_ButtonTest_Click(object sender, EventArgs e)
{
    textBox1.AppendText(DateTime.Now.ToString() + " [" + Thread.CurrentThread.ManagedThreadId + "] Started Test ..." + Environment.NewLine);
    Task<string> l_Task = WaitAsynchronouslyAsync();
    //WaitAsynchronouslyAsync();

    //textBox1.AppendText(l_Result);
}

private void LongComputation()
{
    Console.WriteLine(DateTime.Now.ToString() + " [" + Thread.CurrentThread.ManagedThreadId + "] Generating random string ...");

    string l_RandomString = GetRandomString(10000000);

    Console.WriteLine(DateTime.Now.ToString() + " [" + Thread.CurrentThread.ManagedThreadId + "] Random string generated.");
}

/// <summary>Get random string with specified length</summary>
/// <param name="p_Length">Requested length of random string</param>
/// <param name="p_NoDots">Use case of this is unknown, but assumed to be importantly needed somewhere. Defaults to true therefore.
/// But due to huge performance implication, added this parameter to switch this off.</param>
/// <returns>Random string</returns>
public static string GetRandomString(int p_Length, bool p_NoDots = true)
{
    StringBuilder l_StringBuilder = new StringBuilder();
    string l_RandomString = string.Empty;

    while (l_StringBuilder.Length <= p_Length)
    {
        l_RandomString = (p_NoDots ? System.IO.Path.GetRandomFileName().Replace(".", string.Empty) : System.IO.Path.GetRandomFileName());
        l_StringBuilder.Append(l_RandomString);
    }

    l_RandomString = l_StringBuilder.ToString(0, p_Length);
    l_StringBuilder = null;

    return l_RandomString;
}

As you can see from the output, there are multiple threads used - not by async/await, but by Task.Run():

04.11.2016 12:38:06 [10] Entered WaitAsynchronouslyAsync()
04.11.2016 12:38:17 [10] Task.Delay done, starting random string generation now ...
04.11.2016 12:38:17 [12] Generating random string ...
04.11.2016 12:38:21 [12] Random string generated.
04.11.2016 12:38:21 [10] Leaving WaitAsynchronouslyAsync() ...

This is as usual as it ever have been, but me personally needed this explicit example to understand what's going on and to separate what's done by async/await and what's done by Task.

Solution 3:

Very good explanation for your question is here https://blogs.msdn.microsoft.com/pfxteam/2012/01/20/await-synchronizationcontext-and-console-apps/

When your console application’s Main method is invoked, SynchronizationContext.Current will return null. That means that if you invoke an asynchronous method in your console app, unless you do something special, your asynchronous methods will not have thread affinity: the continuations within those asynchronous methods could end up running “anywhere.”