0

让我们编写简单的控制台应用程序:

    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 获取与当前进程关联的所有线程。

4

1 回答 1

2

您的线程几乎立即退出。Sleep(0) 不是永远的睡眠,它只是一个收益。如果没有其他可运行线程,则对 Sleep(0) 的调用只会返回而不产生时间片。您的线程在调用 Sleep 后立即退出。

做一个更长的 Sleep() 来测试这个。

于 2012-06-26T23:46:21.283 回答