0

I wrote a simple code. The machine has 32 threads. At the twentieth second, I see the number 54 in the console. This means that 54 tasks have started. Each task uses thread suspension. I don't understand why tasks continue to run if tasks have already been created and started in all possible threads and the thread suspension code is running in each task.

What's going on, how does it work?

enter image description here

void MyMethod(int i)
{
    Console.WriteLine(i);
    Thread.Sleep(int.MaxValue);
}

Console.WriteLine(Environment.ProcessorCount);

for (int i = 0; i < int.MaxValue; i++)
{
    Thread.Sleep(50);
    int j = i;
    Task.Run(() => MyMethod(j));
}

And why does this code create so many tasks? (Environment.ProcessorCount => 32)

enter image description here

using System.Net;
    
    void MyMethod(int i)
    {
        Console.WriteLine(WebRequest.Create("https://192.168.1.1").GetResponse().ContentLength);
    }
    
    for (int i = 0; i < Environment.ProcessorCount; i++)
    {
        int j = i;
        Task.Run(() => MyMethod(j));
    }
    
    Thread.Sleep(int.MaxValue);
  • 1
    I guess this might help, I just came across this ( https://stackoverflow.com/questions/19093936/multiple-tasks-for-a-few-threads ) – Avdhan Tyagi Aug 12 '22 at 02:13

1 Answers1

4

The Task.Run method runs the code on the ThreadPool, and the ThreadPool creates more threads when it becomes saturated. Initially it creates immediately on demand as many threads as the number of cores. After that point it is said to be saturated, and creates one new thread every second until the demand is satisfied. This rate is not documented. It is found by experimentation on .NET 6, and might change in future .NET versions.

You are able to control the saturation threshold with the ThreadPool.SetMinThreads method. For example ThreadPool.SetMinThreads(100, 100). If you give it too large values, this method does nothing and returns false.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
  • Thank you. Added a second question. If it doesn't bother you. Why so many tasks? –  Aug 12 '22 at 02:44
  • @NikVladi to be honest I am not familiar with the `Tasks` window of Visual Studio. I don't use the debugging features too much. My guess is that the `WebRequest.Create` method creates internally more than one task to do its job. – Theodor Zoulias Aug 12 '22 at 02:53
  • I see the same thing on .NET 5, .NET Framework: 4.7.8 and 4.8... Thank you. –  Aug 12 '22 at 03:42