Does creating multiple tasks create the same numbe

2019-05-26 23:06发布

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)

2条回答
可以哭但决不认输i
2楼-- · 2019-05-26 23:39

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.

查看更多
欢心
3楼-- · 2019-05-26 23:43

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.

查看更多
登录 后发表回答