我有这个方法:
/// <summary>
/// Waits for all threads in the thread pool to be finished.
/// </summary>
/// <param name="maxWaitingTime">Maximum time to wait in seconds</param>
/// <returns>true if all threads in pool are finished before maxWaitingTime. False if maxWaitingTime is hit </returns>
public bool WaitForThreads(int maxWaitingTime)
{
int maxThreads = 0;
int placeHolder = 0;
int availableThreads = 0;
while (maxWaitingTime > 0)
{
System.Threading.ThreadPool.GetMaxThreads(out maxThreads, out placeHolder);
System.Threading.ThreadPool.GetAvailableThreads(out availableThreads, out placeHolder);
//Stop if all threads are available
if (availableThreads == maxThreads)
{
return true;
}
System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(1000));
--maxWaitingTime;
}
return false;
}
我在控制台应用程序中使用它来等待一段时间,以便线程池正在处理的所有任务都完成。我已将最大线程数设置为 8,但不知何故,可用线程永远不会达到最大线程数,总是有一个线程仍然忙碌。
我在想这个方法是在线程池中调用的,即使我直接从 program.cs 调用这个方法。
如果线程池中运行线程,如何在 Visual Studio 的线程窗口中查看?