本文介绍了使用TPL如何设置最大线程池大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用TPL使用函数 Task.Factory.StartNew()向系统线程池中添加新任务。唯一的问题是,我添加了很多线程,我认为它是创建太多的我的处理器来处理。是否有一种方法可以在此线程池中设置最大线程数?

解决方案

默认 TaskScheduler (从 TaskScheduler.Default 获取)是类型(内部类) ThreadPoolTask​​Scheduler 。这个实现使用 ThreadPool 类来排队任务(如果任务不是使用 TaskCreationOptions.LongRunning - 在这种情况下为每个任务创建一个新的线程。)



所以,如果你想限制线程数可用于通过 new Task(()=> Console.WriteLine(In task))创建的任务 ,你可以这样限制全局线程池中的可用线程:

  //限制线程池大小
int workerThreads, completionPortThreads;
ThreadPool.GetMaxThreads(out of workerThreads,out completionPortThreads);
workerThreads = 32;
ThreadPool.SetMaxThreads(workerThreads,completionPortThreads);

调用 ThreadPool.GetMaxThreads()以避免收缩 completionPortThreads



请注意,这可能是一个坏主意 - 指定的调度器,并且任何数量的其他类使用默认ThreadPool,设置大小太低可能会导致副作用:Starvation等。


I am using the TPL to add new tasks to the system thread pool using the function Task.Factory.StartNew(). The only problem is that I am adding a lot of threads and I think it is creating too many for my processor to handle. Is there a way to set a maximum number of threads in this thread pool?

解决方案

The default TaskScheduler (obtained from TaskScheduler.Default) is of type (internal class) ThreadPoolTaskScheduler. This implementation uses the ThreadPool class to queue tasks (if the Task isn't created with TaskCreationOptions.LongRunning - in this case a new thread is created for each task).

So, if you want to limit the # of threads available to Task objects created via new Task(() => Console.WriteLine("In task")), you can limit the available threads in the global threadpool like this:

// Limit threadpool size
int workerThreads, completionPortThreads;
ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
workerThreads = 32;
ThreadPool.SetMaxThreads(workerThreads, completionPortThreads);

The call to ThreadPool.GetMaxThreads() is done to avoid shrinking the completionPortThreads.

Note that this may be a bad idea - since all Tasks without a specified scheduler, and any number of other classes use the default ThreadPool, setting the size too low could cause side-effects: Starvation, etc.

这篇关于使用TPL如何设置最大线程池大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:45