简体   繁体   中英

Does Parallel.ForEach() destroys the threads immediately after execution?

I have code block which uses Parallel.ForEach, something like below

    public void ReadValuesFromServers()
    {
        Parallel.ForEach(serverList, server => 
        {
           //Some logic
        });
    }

I will be calling ReadValuesFromServers() method frequently(every 1 or 2 secs), I understand that Parallel.ForEach() internally uses thread to process the commands. I would like to know whether, the threads which are created by Parallel.ForEach(), will it be destroyed immediately after executing the Parallel.ForEach() or will it be maintained in ThreadPool for next set of execution.

Or is it better to use List<Task> in this case?

It depends on the ThreadPool heuristics. If the ThreadPool decides that the current number of pooled threads are too many compared to the current demand for work, it will automatically decommission some threads. Otherwise, if there is frequent demand for work to be done, the same threads will be reused over and over again by the ThreadPool .

This is the expected behavior if you use the default ParallelOptions . But it is also possible to specify a ParallelOptions.TaskScheduler different than the TaskScheduler.Default , potentially a custom one, and enforce any kind of thread usage scheme that you can imagine (and you are able to implement).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM