Does creating multiple tasks create the same numbe

2019-05-26 23:48发布

问题:

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)

回答1:

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.



回答2:

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.