user809808
user809808

Reputation: 789

How to understand Process.Threads.Count results? What this variable display?

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] Why p.Threads.Count differ from Process.GetCurrentProcess().Threads.Count ?

Upvotes: 4

Views: 784

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502686

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.

Upvotes: 5

Related Questions