D J
D J

Reputation: 7028

how TPL decide the number of threads to be created

Even if I am using TPL from long time but since it sounds new to me. I want to understand the TPL with thread pool and I created a POC in .NET framework 4.0 for that which is as below.

 public class CustomData
 {
    public long CreationTime;
    public int Name;
    public int ThreadNum;
 }

 public class TPLSample
 {
    public int MaxThread = 0;
    public void Start()
    {
        Task[] taskArray = new Task[10000];
        for (int i = 0; i < taskArray.Length; i++)
        {
            taskArray[i] = Task.Factory.StartNew((Object obj) =>
            {
                var data = new CustomData() { Name = i, CreationTime = DateTime.Now.Ticks };
                Thread.SpinWait(10000);
                data.ThreadNum = Thread.CurrentThread.ManagedThreadId;
                if (Thread.CurrentThread.ManagedThreadId > MaxThread)
                {
                    MaxThread = Thread.CurrentThread.ManagedThreadId;
                }
                Console.WriteLine("Task #{0} created at {1} on thread #{2}.",
                                  data.Name, data.CreationTime, data.ThreadNum);
            },
                                                 i);
        }
        Task.WaitAll(taskArray);
        Console.WriteLine("Max no of threads {0}", MaxThread);
    }
}

I found that only 14 threads are created to do this task!!

But why the 14? what is the criteria ? can I increase or decrease this number? How can I change this number. Is it really possible or totally abstracted from a developer.

Upvotes: 0

Views: 591

Answers (1)

techvice
techvice

Reputation: 1301

From MSDN:

The number of operations that can be queued to the thread pool is limited only by available memory; however, the thread pool limits the number of threads that can be active in the process simultaneously. Beginning with the .NET Framework 4, the default size of the thread pool for a process depends on several factors, such as the size of the virtual address space. A process can call the GetMaxThreads method to determine the number of threads.

Another MSDN:

The TPL may employ various optimizations, especially with large numbers of delegates.

Another SO question about this. Hopefully this will quench your thirst.

Upvotes: 2

Related Questions