Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Resource Monitor" shows me more threads than the two that I wrote on my program

Tags:

I am learning about Threads. Im using C# with .NET Framework 4.5.2 and Windows 10 x64.

I wrote a simple program with two threads and one large loop in each one:

class Program
{
    static void Main(string[] args)
    {
        Thread t = new Thread(foo);
        t.Start();
        for (int i = 0; i < 99999999; i++)
        {
            Console.WriteLine("x");
        }

    }

    static void foo()
    {
        for (int i = 0; i < 99999999; i++)
        {
            Console.WriteLine("y");
        }
    }
}

And when I run the final release of the program, in "Resource Monitor" I read it is running more than two threads.

It leads me to understand that we can't have a real control of how our application will be executed, only we can say "I want to run X at the same time than Y", but no a strict (real) control of number of threads that will be created. Is that correct?

I want to know the explanation of this behaviour.

Here a image of what I've just explained: threads

like image 941
Pablo De Luca Avatar asked Jul 24 '16 18:07

Pablo De Luca


1 Answers

You have at least three threads when you run your application without a debugger attached and without creating any additional thread.

Remember that the garbage collector works on a separate thread. Also the finalizer works on a separate thread. The Main Thread is Trivial in this discussion.

When you see more threads, you need to keep in mind that when debugging using Visual Studio, there are debug-related threads running.

To test that, create a simple program like the below :

class Program
{
    static void Main(string[] args)
    {
        Console.ReadKey();
    }
}

Build your application, and run it using the Executable (Without Visual Studio Debugger Attached), you would see exactly 3 threads in the resource monitor.

like image 148
Zein Makki Avatar answered Sep 28 '22 01:09

Zein Makki