Search code examples
c#threadpool

Why Thread 2 not available?


In below little console application, I'm printing main thread Id and the 5 other thread, it's printing 1, 3,4,5,6,7, but not 2. Is thread 2 not available and how this number is generated?

static void Main(string[] args)
    {
        Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId}");

        Enumerable.Range(0, 5).ToList().ForEach(f =>
        {
            new Thread(() =>
            {
                Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId}");
                Thread.Sleep(1000);
            }).Start();

        });
        Console.ReadLine();
    }

Thread 1 Thread 3 Thread 4 Thread 5 Thread 6 Thread 7


Solution

  • Thread with Id=2 is garbage collector thread. You can check its Id by running finalizer:

    class Test
    {
        ~Test()
        {
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
        }
    }
    
    static void Main(string[] args)
    {
        Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
    
        var test = new Test();
        test = null;
        GC.Collect();
    }
    

    Prints:

    1
    2