我写了一个非常简单的检查来告诉我我在哪个线程上,然后添加了一些async await代码。我注意到第一次检查时我在thread1上,然后是thread3,而且在我的代码执行期间我从未返回到thread1。
有人能解释一下为什么在await之后我不会返回调用await的主线程吗?WhatThreadAmI()的输出如下:
有人能解释一下为什么在await之后我不会返回调用await的主线程吗?WhatThreadAmI()的输出如下:
**********************
Main - 17 -- True
**********************
**********************
CountAsync - 37 -- False
**********************
**********************
Main - 22 -- False
**********************
**********************
Main - 29 -- False
**********************
示例代码:
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;
}