I read the Microsoft document about async and await. It says:
The async and await keywords don't cause additional threads to be created.
But I run the below code
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace Examples.AdvancedProgramming.AsynchronousOperations
{
public class AsyncMain
{
static void Main()
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
Task task = Test();
task.Wait();
}
public async static Task Test()
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
await Task.Delay(1000);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
}
}
The result is
1
1
4
It is obvious that the
await Task.Delay(1000);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
is run in another thread. Why does the document says there is no thread created?
I have read the previous question Does the use of async/await create a new thread?, but it does not answer my question, the answer there just copy pastes from a Microsoft source. Why do I see different thread IDs in my test?
I always encourage people to read my async intro, and follow up with async best practices. In summary:
await by default captures a "context", and resumes executing the async method in that context. In this case, the context is the thread pool context. So, that's why you're seeing Test resume executing on a thread pool thread.
async and await by themselves do not create any additional threads; if you do the same in a UI app, for example, the "context" would be the UI thread, and Test would resume executing on that UI thread. But the context that is implicitly captured by await is what is responsible for scheduling the asnc continuation, and the context in this example just schedules it to the thread pool.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With