Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If async/await doesn't create new thread then explain this code

I've read this thread which claims with reference to msdn with idea that async/await doesn't create new threads. Please look at following code:

static class Program
{
    static void Main(string[] args)
    {
        var task = SlowThreadAsync();
        for(int i = 0; i < 5; i++)
        {
            Console.WriteLine(i * i);
        }
        Console.WriteLine("Slow thread result {0}", task.Result);
        Console.WriteLine("Main finished on thread {0}", Thread.CurrentThread.ManagedThreadId);
        Console.ReadKey();
    }

    static async Task<int> SlowThreadAsync()
    {
        Console.WriteLine("SlowThreadAsync started on thread {0}", Thread.CurrentThread.ManagedThreadId);
        await Task.Delay(2000);
        Console.WriteLine("SlowThreadAsync completed on thread {0}", Thread.CurrentThread.ManagedThreadId);
        return 3443;

    }
}

As result of this code I got different ThreadId. Why the same thread gets different ThreadId?

different threads

like image 568
Yuriy Zaletskyy Avatar asked Sep 08 '15 08:09

Yuriy Zaletskyy


People also ask

Does async await create a new thread?

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. The method runs on the current synchronization context and uses time on the thread only when the method is active.

What happens if we dont use async await?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

Does async code run in different thread?

No, it does not. It MAY start another thread internally and return that task, but the general idea is that it does not run on any thread.

Does async await block the thread?

The await operator doesn't block the thread that evaluates the async method. When the await operator suspends the enclosing async method, the control returns to the caller of the method.


2 Answers

You're using a console application for your example. This effects greatly the outcome of your test. A console application has no custom SynchronizationContext (like Winforms, WPF and ASP.NET have), hence it uses the ThreadPoolTaskScheduler to schedule continuations on an arbitrary thread-pool thread. Try this same example in a UI application and you'll see the continuation invoked on the same thread.

like image 59
Yuval Itzchakov Avatar answered Nov 15 '22 18:11

Yuval Itzchakov


What the articles you linked are trying to get across is that calling async methods does not guarantee that any of the code runs on a separate thread. So if you do want to guarantee this, you have to do it manually. In particular they're not trying to say that an async method will always run on the same thread as the calling method, because this is blatantly false in many scenarios.

like image 27
Joren Avatar answered Nov 15 '22 18:11

Joren