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

2024-02-10

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

    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);
    }

您认为您会在结果中看到什么?

[问题1] 为什么 p.Threads.Count 与 Process.GetCurrentProcess().Threads.Count 不同?


你需要打电话Process.Refresh() http://msdn.microsoft.com/en-us/library/system.diagnostics.process.refresh.aspx在你获取之前Threads每次都访问属性,以避免看到缓存的结果。

这样做,您就会看到您期望的结果。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何理解Process.Threads.Count结果?这个变量显示什么? 的相关文章

随机推荐