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

问题描述

我正在使用 TPL 使用函数 Task.Factory.StartNew() 向系统线程池添加新任务.唯一的问题是我添加了很多线程,我认为它为我的处理器创建了太多无法处理的线程.有没有办法设置这个线程池中的最大线程数?

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?

推荐答案

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

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).

因此,如果您想限制通过 new Task(() => Console.WriteLine("In task")) 创建的 Task 对象可用的线程数量code>,你可以像这样限制全局线程池中的可用线程:

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);

调用 ThreadPool.GetMaxThreads() 是为了避免缩小 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