Does .NET resume an await continuation on a new different thread pool thread or reuse the thread from a previous resumption?
Let's image below C# code in a .NET Core console application:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace NetCoreResume
{
class Program
{
static async Task AsyncThree()
{
await Task.Run(() =>
{
Console.WriteLine($"AsyncThree Task.Run thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
});
Console.WriteLine($"AsyncThree continuation thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
}
static async Task AsyncTwo()
{
await AsyncThree();
Console.WriteLine($"AsyncTwo continuation thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
}
static async Task AsyncOne()
{
await AsyncTwo();
Console.WriteLine($"AsyncOne continuation thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
}
static void Main(string[] args)
{
AsyncOne().Wait();
Console.WriteLine("Press any key to end...");
Console.ReadKey();
}
}
}
It will output:
AsyncThree Task.Run thread id:4
AsyncThree continuation thread id:4
AsyncTwo continuation thread id:4
AsyncOne continuation thread id:4
Press any key to end...
I have tried to add ConfigureAwait(false)
after each await Task
, but it will get the same result.
As we can see, it seems like all await continuations reused the thread created in Task.Run
of AsyncThree()
method.
I want to ask if .NET will always resume the await continuation on previous resumption thread, or it will apply a new different thread from thread pool in some occasions?
I knew there is answer the continuation will resume on a thread pool thread in below discussion:
async/await. Where is continuation of awaitable part of method performed?
Let's exclude the SynchronizationContext
case in above link, since we are now discussing a .NET console application. But I want to ask it seems like that thread pool thread in my example is always thread id 4
, I don't know whether it is because thread id 4
is always free in the thread pool, so every continuation reuse it by coincidence, or .NET has mechanism will reuse the previous resumption thread as much as possible?
Is there any possibility each continuation will resume on a different thread pool thread like below?
AsyncThree Task.Run thread id:4
AsyncThree continuation thread id:5
AsyncTwo continuation thread id:6
AsyncOne continuation thread id:7
Press any key to end...