jgauffin
jgauffin

Reputation: 101150

How to TPL determine the number of threads to use?

I've helped a client with an application which stopped doing it's work after a while (it eventually started doing work again).

The problem was that when a Task failed it used Thread.Sleep for 5 seconds (in the task). As there could be up to 800 tasks queued every two second you can imagine the problem if many of those jobs fails and invoked Thread.Sleep. None of those jobs were marked with TaskCreationOptions.LongRunning.

I rewrote the tasks so that Thread.Sleep (or Task.Delay for that matter) wasn't nessacary.

However, I'm interested in what the TaskScheduler (the default) did in that scenario. How and when do it increase the number of threads?

Upvotes: 3

Views: 1018

Answers (1)

Neil Mountford
Neil Mountford

Reputation: 2001

According to MSDN

Behind the scenes, tasks are queued to the ThreadPool, which has been enhanced with algorithms (like hill-climbing) that determine and adjust to the number of threads that maximizes throughput.

The ThreadPool will have a maximum number of threads depending on the environment. As you create more Tasks the pool can run them concurrently until it reaches its maximum number of threads, at which point any further tasks will be queued.

If you want to find out the maximum number of ThreadPool threads you can use System.Threading.ThreadPool.GetMaxThreads (you need to pass in two out int parameters, one that will be populated with the number of maximum worker threads and another that will be populated with the maximum number of asynchronous I/O threads).

If you want to get a better idea of what is happening in your application at runtime you can use Visual Studio's threads window by going to Debug -> Windows -> Threads (The entry will only be there when you are debugging so you'll need to set a break point in your application first).

This post is possibly of interest. It would seem the default task scheduler simply queues the task up in the ThreadPool's queue unless you use TaskCreationOptions.LongRunning. This means that it's up to the ThreadPool to decide when to create new threads.

Upvotes: 2

Related Questions