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

时间:2012-06-17 22:36:04

标签: multithreading c#-4.0 task-parallel-library

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

4 个答案:

答案 0 :(得分:15)

默认TaskScheduler(从TaskScheduler.Default获取)属于(内部类)ThreadPoolTaskScheduler。此实现使用ThreadPool类对任务进行排队(如果Task未使用TaskCreationOptions.LongRunning创建 - 在这种情况下,将为每个任务创建一个新线程。)

因此,如果要限制通过Task创建的new Task(() => Console.WriteLine("In task"))个对象可用的线程数,可以限制全局线程池中的可用线程,如下所示:

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

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

请注意,这可能是个坏主意 - 因为没有指定调度程序的所有任务以及任何数量的其他类都使用默认的ThreadPool,将大小设置得太低可能会导致副作用:Starvation等。

答案 1 :(得分:6)

通常,TPL确定一个好的“默认”线程池大小。如果您确实需要更少的线程,请参阅How to: Create a Task Scheduler That Limits the Degree of Concurrency

答案 2 :(得分:4)

您应首先调查您的性能问题。有许多问题可能导致利用率降低:

  • 在没有LongRunningTask选项的情况下安排长时间运行的任务
  • 尝试打开两个以上并发连接到同一个网址
  • 阻止访问同一资源
  • 尝试使用多线程的Invoke()访问UI线程

在任何情况下,您都会遇到可扩展性问题,只能通过减少并发任务的数量来解决这个问题。您的程序将来可能在两核,四核或八核机器上运行。限制计划任务的数量只会导致CPU资源的浪费。

答案 3 :(得分:-1)

通常TPL调度程序应该很好地选择要同时运行的任务数,但是如果你真的想控制它My blog post显示了如何使用Tasks和with Actions执行此操作,并提供您可以下载并运行的示例项目,以查看两者的实际效果。

您可能希望明确限制同时运行的任务数量的示例是您何时调用自己的服务并且不想使服务器过载。

对于您所描述的内容,听起来您可能会从确保使用异步/等待任务以防止不必要的线程消耗中获益更多。这将取决于您是否正在执行CPU绑定工作或任务中的IO绑定工作。如果它受IO限制,那么你可以从使用async / await中受益匪浅。

无论如何,您询问如何限制并发运行的任务数量,因此这里有一些代码来说明如何使用操作和任务执行此操作。

使用操作

如果使用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);
相关问题