i Have the following code:
static void Main(string[] args)
{
Run1();
Run2().Wait();
}
static async Task DoAsyncWork()
{
await Task.Delay(2000);
}
static async Task Run2()
{
var tid = Thread.CurrentThread.ManagedThreadId;
await DoAsyncWork();
Console.WriteLine(tid == Thread.CurrentThread.ManagedThreadId);
}
static void Run1()
{
var tid = Thread.CurrentThread.ManagedThreadId;
DoAsyncWork().Wait();
Console.WriteLine(tid == Thread.CurrentThread.ManagedThreadId);
}
What will be the output:
Sometimes True sometimes false.
True
False
False
True
Sometimes True sometimes false.
True
True
I think 3 is the correct answer, but when i run the code all time i get:
True
False
I know why the first print is True but anyone can explain me why when i run the code allways i get False? (how i can get True in second print?)
Thank!
Console apps do not have a synchronization context so
await
is not able to return to the previous thread. This is why you are seeing a different thread id inRun2
.You can read more about this here.