使用TPL如何设置最大线程池大小

编程入门 行业动态 更新时间:2024-10-09 00:44:46
本文介绍了使用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如何设置最大线程池大小

本文发布于:2023-11-12 02:01:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580189.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   如何设置   大小   TPL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!