如何使用VS C# 2015调试器检查线程是否返回到线程池?
在我的情况下,问题在于无法通过逐行调试检测到。
async Task foo()
{
int y = 0;
await Task.Delay(5);
// (1) thread 2000 returns to thread pool here...
while (y<5) y++;
}
async Task testAsync()
{
Task task = foo();
// (2) ... and here thread 2000 is back from the thread pool, to run the code below. I want
// to confirm that it was in the thread pool in the meantime, using debugger.
int i = 0;
while (i < 100)
{
Console.WriteLine("Async 1 before: " + i++);
}
await task;
}
在运行在线程2000上的
testAsync
的第一行中,调用了foo
。一旦遇到await Task.Delay(5)
,线程2000返回到线程池(据说,我正在尝试确认这一点),并等待Task.Delay(5)
完成。同时,控制权返回给调用者,并且testAsync
的第一个循环在线程2000上执行。因此,在两个连续的代码行之间,线程返回到线程池,然后从那里回来。如何使用调试器确认这一点?可能使用线程调试器窗口?
为了更清楚地说明我的问题:
foo
正在线程2000上运行。有两种可能的情况:1. 当它遇到
await Task.Delay(5)
时,线程2000会短暂地返回到线程池,控制权返回到调用者,在第二行执行(使用从线程池中取出的线程2000)。如果是这样,你无法轻松地检测到它,因为在线程池中的线程2000在两个连续的代码行之间的时间内。
2. 当它遇到await Task.Delay(5)
时,线程2000不会返回到线程池,而是立即执行testAsync
中从第二行开始的代码。我想验证哪一个是真正发生的。
await Task.Yield();
代替await Task.Delay(5);
。 - Ivan Stoev