Does multiple tasks create the same number of threads?

When I create such an array of such tasks:

var taskArray = new Task<double>[] { Task.Factory.StartNew(() => new Random().NextDouble()), Task.Factory.StartNew(() => new Random().NextDouble()), Task.Factory.StartNew(() => new Random().NextDouble()) }; 

Will it create 3 threads for sure, or is it up to the CLR to create threads on its own?

So, if I execute this in a web request, does this mean that at least 4 threads will be created to properly service the request? (web request + 1 for each task)

+2
source share
2 answers

Will it create 3 threads for sure, or is it up to the CLR to create threads on its own?

Last. In particular, since these tasks are performed so quickly, I won’t be surprised if all of them are executed in the same thread (although this is not the thread called StartNew ), especially if this happens in a β€œclean” process, and the thread pool shouldn't have started many threads. (IIRC, the thread pool starts only one new thread every 0.5 seconds, which will give a lot of time to complete all your tasks in one thread.)

You can use your own TaskScheduler if you want, but it will be relatively extreme.

You should read the MSDN article for task schedulers (including the default) for more information.

+5
source

There is no simple answer. It depends on the resources available on the server. It will set the queue, and if the server can start 3 threads at the same time (it will start it), otherwise it will stand in line.

0
source

All Articles