如何理解Process.Threads.Count结果?这是什么变量显示?变量、结果、这是什么、Process

2023-09-04 11:22:34 作者:殇 ╖循环式

让我们编写简单的控制台应用程序(调试模式):

Lets write simple console application (debug mode):

    static void Main(string[] args)
    {
        Process p = Process.GetCurrentProcess();

        IList<Thread> threads = new List<Thread>();
        Console.WriteLine(p.Threads.Count);
        for(int i=0;i<30;i++)
        {
            Thread t = new Thread(Test);
            Console.WriteLine("Before start: {0}", p.Threads.Count);
            t.Start();
            Console.WriteLine("After start: {0}", p.Threads.Count);
        }
        Console.WriteLine(Process.GetCurrentProcess().Threads.Count);
        Console.ReadKey();
    }

    static void Test()
    {
        for(int i=0;i<100;i++)Thread.Sleep(1);
    }

你认为你会看到的结果?

What do you think you will see in results?

[Q1]为什么从Process.GetCurrentProcess()。Threads.Count?p.Threads.Count不同

推荐答案

您需要调用的 Process.Refresh() 你取主题属性之前,每个时间,以避免看到缓存的结果。

You need to call Process.Refresh() before you fetch the Threads property each time, to avoid seeing the results of caching.

做到这一点,你会看到你所期望的结果。

Do that and you'll see the results you expect.