loyalflow
loyalflow

Reputation: 14879

Does creating multiple tasks create the same number of threads?

When I create an array of tasks like this:

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

Will this create 3 threads for sure, or it is up to the CLR to create threads as it sees fit?

So if I perform this in a web request, this means there will be at least 4 threads created to service the request correct? (the web request + 1 for each task)

Upvotes: 2

Views: 1103

Answers (2)

Kamil Lach
Kamil Lach

Reputation: 4629

No easy answer. It depend on available resources on server. It'll setup queue and if server can run 3 thread in same time (it run it), otherwise it'll queue it.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500475

Will this create 3 threads for sure, or it is up to the CLR to create threads as it sees fit?

The latter. In particular, as those tasks complete so quickly I wouldn't be surprised if they all executed on the same thread (although not the same thread as the one calling StartNew) - particularly if this is in a "clean" process and the thread pool hasn't had to fire up many threads yet. (IIRC, the thread pool only starts one new thread every 0.5 seconds, which would give plenty of time for all of your tasks to execute on a single thread.)

You can use your own custom TaskScheduler if you really want to, but that would be relatively extreme.

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

Upvotes: 6

Related Questions