I wrote a really simple check that tells me what thread I am on and then added some async await code. I noticed that the first time I check I am on thread1, then thread3, and I never return to thread1 during my code execution.
Can anyone explain to me why after the await I don't return to the main thread that called await? The output of WhatThreadAmI() goes as follows:
********************** Main - 17 -- True ********************** ********************** CountAsync - 37 -- False ********************** ********************** Main - 22 -- False ********************** ********************** Main - 29 -- False ********************** Example code:
class Program { static Thread mainThread; public static async Task Main(string[] args) { mainThread = Thread.CurrentThread; WhatThreadAmI(); Console.WriteLine("Counting until 100 million in 5 seconds ..."); var msWait = await CountAsync(); WhatThreadAmI(); Console.WriteLine($"Counting to 100 million took {msWait} milliseconds."); Console.WriteLine("Press any key to exit"); Console.ReadKey(); WhatThreadAmI(); } static async Task<String> CountAsync() { return await Task.Run(() => { WhatThreadAmI(); Task.Delay(TimeSpan.FromSeconds(5)).Wait(); var startTime = DateTime.Now; var num = 0; while (num < 100000000) { num += 1; } return (DateTime.Now - startTime).TotalMilliseconds.ToString(); }); } static void WhatThreadAmI([CallerMemberName]string Method = "", [CallerLineNumber]int Line = 0) { const string dividor = "**********************"; Debug.WriteLine(dividor); Debug.WriteLine($"{Method} - {Line} -- {IsMainThread()}"); Debug.WriteLine(dividor); } public static bool IsMainThread() => mainThread == Thread.CurrentThread; }