我有以下简单的控制台应用程序:
class Program
{
private static int times = 0;
static void Main(string[] args)
{
Console.WriteLine("Start {0}", Thread.CurrentThread.ManagedThreadId);
var task = DoSomething();
task.Wait();
Console.WriteLine("End {0}", Thread.CurrentThread.ManagedThreadId);
Console.ReadLine();
}
static async Task<bool> DoSomething()
{
times++;
if (times >= 3)
{
return true;
}
Console.WriteLine("DoSomething-1 sleeping {0}", Thread.CurrentThread.ManagedThreadId);
await Task.Run(() =>
{
Console.WriteLine("DoSomething-1 sleep {0}", Thread.CurrentThread.ManagedThreadId);
Task.Yield();
});
Console.WriteLine("DoSomething-1 awake {0}", Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("DoSomething-2 sleeping {0}", Thread.CurrentThread.ManagedThreadId);
await Task.Run(() =>
{
Console.WriteLine("DoSomething-2 sleep {0}", Thread.CurrentThread.ManagedThreadId);
Task.Yield();
});
Console.WriteLine("DoSomething-2 awake {0}", Thread.CurrentThread.ManagedThreadId);
bool b = await DoSomething();
return b;
}
}
与输出
Start 1
DoSomething-1 sleeping 1
DoSomething-1 sleep 3
DoSomething-1 awake 4
DoSomething-2 sleeping 4
DoSomething-2 sleep 4
DoSomething-2 awake 4
DoSomething-1 sleeping 4
DoSomething-1 sleep 3
DoSomething-1 awake 3
DoSomething-2 sleeping 3
DoSomething-2 sleep 3
DoSomething-2 awake 3
End 1
我知道控制台应用程序不提供 SynchronizationContext,因此任务在线程池上运行。但令我惊讶的是,当从 await in 恢复执行时DoSomething
,我们在 await 内部的同一线程上。我曾假设当我们继续执行 awaiting 方法时,我们要么返回到我们等待的线程,要么完全在另一个线程上。
有谁知道为什么?我的例子在某些方面有缺陷吗?