让我们编写简单的控制台应用程序:
static void Main(string[] args)
{
IList<Thread> threads = new List<Thread>();
Console.WriteLine((Process.GetCurrentProcess().Threads).OfType<ProcessThread>().Where(thread => thread.ThreadState == ThreadState.Wait).Count());
for(int i=0;i<30;i++)
{
Thread t = new Thread(Test);
Console.WriteLine("Before start: {0}", (Process.GetCurrentProcess().Threads).OfType<ProcessThread>().Where(thread => thread.ThreadState == ThreadState.Wait).Count());
t.Start();
Console.WriteLine("After start: {0}", (Process.GetCurrentProcess().Threads).OfType<ProcessThread>().Where(thread => thread.ThreadState == ThreadState.Wait).Count());
}
Console.WriteLine((Process.GetCurrentProcess().Threads).OfType<ProcessThread>().Where(thread => thread.ThreadState == ThreadState.Wait).Count());
Console.ReadKey();
}
static void Test()
{
Thread.Sleep(0);
}
如您所见,我们在流程中创建了30个等待线程。他们在哪里? MSDN:
使用ProcessThread获取所有与当前进程关联的线程。
答案 0 :(得分:2)
您的线程几乎立即退出。睡眠(0)不是永远的睡眠,它只是一个收益。如果没有其他可运行的线程,则对Sleep(0)的调用只返回而不会产生时间片。在调用Sleep之后,您的线程会立即退出。
再做一次Sleep()来测试它。