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

13

我正在使用TPL,使用函数Task.Factory.StartNew()将新任务添加到系统线程池中。唯一的问题是,我正在添加大量线程,我认为它会创建过多的线程,超出了处理器的处理能力。是否有一种方法可以在此线程池中设置最大线程数?


4
不要只是想,要找出它是否真实。 - svick
4个回答

16

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

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

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

调用 ThreadPool.GetMaxThreads() 是为了避免缩小 completionPortThreads

注意,这可能是一个不好的想法 - 因为所有没有指定调度程序的任务和任意数量的其他类都使用默认线程池,设置大小过低可能会引起副作用:饥饿等。


1
在.NET Core 3.1中,这是无效的。ThreadPool.SetMaxThreads(workerThreads, completionPortThreads);不再起作用。 - Will Huang

7

4
您应该首先调查性能问题。可能会有各种问题导致利用率降低:
  • 调度长时间运行的任务而不使用LongRunningTask选项
  • 尝试同时打开超过两个连接到同一网址
  • 为了访问相同的资源而阻塞
  • 尝试从多个线程使用Invoke()访问UI线程
无论如何,您都存在可伸缩性问题,不能简单地通过减少并发任务的数量来解决。您的程序将来可能在两、四或八核机器上运行。限制计划任务的数量只会导致CPU资源浪费。

1
谢谢你的负评,能解释一下吗?一个常见的 bug 是人们假设任务等同于线程,并尝试限制任务数量,导致性能问题更加严重。 - Panagiotis Kanavos

0
通常情况下,TPL调度程序应该能够很好地选择并发运行任务的数量,但如果您真的想对此进行控制,我的博客文章展示了如何使用Tasks和Actions来实现,并提供了一个可下载和运行的示例项目。
一个你可能想明确限制同时运行的任务数量的例子是当你调用自己的服务时,不希望超载你的服务器。
针对你所描述的情况,似乎使用async/await确保你在任务中使用它可以避免不必要的线程消耗会更加有益。这取决于你的任务是CPU绑定还是IO绑定。如果是IO绑定,则使用async/await可能会极大地受益。
无论如何,你询问如何限制同时运行的任务数量,这里有一些代码展示如何在Actions和Tasks中实现它。

使用Actions

如果使用Actions,你可以使用内置的.Net Parallel.Invoke函数。这里我们将它限制在最多同时运行3个线程。

var listOfActions = new List<Action>();
for (int i = 0; i < 10; i++)
{
    // Note that we create the Action here, but do not start it.
    listOfActions.Add(() => DoSomething());
}

var options = new ParallelOptions {MaxDegreeOfParallelism = 3};
Parallel.Invoke(options, listOfActions.ToArray());

使用任务

由于您在此处使用任务,因此没有内置函数。但是,您可以使用我在博客上提供的函数。

    /// <summary>
    /// Starts the given tasks and waits for them to complete. This will run, at most, the specified number of tasks in parallel.
    /// <para>NOTE: If one of the given tasks has already been started, an exception will be thrown.</para>
    /// </summary>
    /// <param name="tasksToRun">The tasks to run.</param>
    /// <param name="maxTasksToRunInParallel">The maximum number of tasks to run in parallel.</param>
    /// <param name="cancellationToken">The cancellation token.</param>
    public static void StartAndWaitAllThrottled(IEnumerable<Task> tasksToRun, int maxTasksToRunInParallel, CancellationToken cancellationToken = new CancellationToken())
    {
        StartAndWaitAllThrottled(tasksToRun, maxTasksToRunInParallel, -1, cancellationToken);
    }

    /// <summary>
    /// Starts the given tasks and waits for them to complete. This will run, at most, the specified number of tasks in parallel.
    /// <para>NOTE: If one of the given tasks has already been started, an exception will be thrown.</para>
    /// </summary>
    /// <param name="tasksToRun">The tasks to run.</param>
    /// <param name="maxTasksToRunInParallel">The maximum number of tasks to run in parallel.</param>
    /// <param name="timeoutInMilliseconds">The maximum milliseconds we should allow the max tasks to run in parallel before allowing another task to start. Specify -1 to wait indefinitely.</param>
    /// <param name="cancellationToken">The cancellation token.</param>
    public static void StartAndWaitAllThrottled(IEnumerable<Task> tasksToRun, int maxTasksToRunInParallel, int timeoutInMilliseconds, CancellationToken cancellationToken = new CancellationToken())
    {
        // Convert to a list of tasks so that we don&#39;t enumerate over it multiple times needlessly.
        var tasks = tasksToRun.ToList();

        using (var throttler = new SemaphoreSlim(maxTasksToRunInParallel))
        {
            var postTaskTasks = new List<Task>();

            // Have each task notify the throttler when it completes so that it decrements the number of tasks currently running.
            tasks.ForEach(t => postTaskTasks.Add(t.ContinueWith(tsk => throttler.Release())));

            // Start running each task.
            foreach (var task in tasks)
            {
                // Increment the number of tasks currently running and wait if too many are running.
                throttler.Wait(timeoutInMilliseconds, cancellationToken);

                cancellationToken.ThrowIfCancellationRequested();
                task.Start();
            }

            // Wait for all of the provided tasks to complete.
            // We wait on the list of "post" tasks instead of the original tasks, otherwise there is a potential race condition where the throttler&#39;s using block is exited before some Tasks have had their "post" action completed, which references the throttler, resulting in an exception due to accessing a disposed object.
            Task.WaitAll(postTaskTasks.ToArray(), cancellationToken);
        }
    }

然后创建您的任务列表并调用函数以运行它们,例如每次最多同时运行3个,您可以这样做:

var listOfTasks = new List<Task>();
for (int i = 0; i < 10; i++)
{
    var count = i;
    // Note that we create the Task here, but do not start it.
    listOfTasks.Add(new Task(() => Something()));
}
Tasks.StartAndWaitAllThrottled(listOfTasks, 3);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接