System.Threading.Tasks - 限制并发任务的数量

时间:2010-05-24 16:46:25

标签: .net asp.net multithreading task

我刚刚开始在.Net 4.0中查看新的“System.Threading.Tasks”的好处,并且想知道是否有任何构建支持限制一次运行的并发任务的数量,或者如果这应该手动处理。

E.G:如果我需要调用100次计算方法,有没有办法设置100个任务,但只有5个同时执行?答案可能只是创建5个任务,调用Task.WaitAny,并在前一个任务完成时创建一个新任务。我只是想确保如果有更好的方法,我不会错过任何一招。

基本上,有一种内置的方法可以做到这一点:

Dim taskArray() = {New Task(Function() DoComputation1()),
                   New Task(Function() DoComputation2()),
                   ...
                   New Task(Function() DoComputation100())}

Dim maxConcurrentThreads As Integer = 5
RunAllTasks(taskArray, maxConcurrentThreads)

感谢您的帮助。

8 个答案:

答案 0 :(得分:45)

我知道这已经快一年了,但我找到了一种更容易实现的方法,所以我想我会分享:

Dim actionsArray() As Action = 
     new Action(){
         New Action(Sub() DoComputation1()),
         New Action(Sub() DoComputation2()),
         ...
         New Action(Sub() DoComputation100())
      }

System.Threading.Tasks.Parallel.Invoke(New Tasks.ParallelOptions() With {.MaxDegreeOfParallelism = 5}, actionsArray)

瞧!

答案 1 :(得分:27)

我知道这是一个旧线程,但我只是想分享我对这个问题的解决方案:使用信号量。

(这是在C#中)

private void RunAllActions(IEnumerable<Action> actions, int maxConcurrency)
{
    using(SemaphoreSlim concurrencySemaphore = new SemaphoreSlim(maxConcurrency))
    {
        foreach(Action action in actions)
        {
            Task.Factory.StartNew(() =>
            {
                concurrencySemaphore.Wait();
                try
                {
                    action();
                }
                finally
                {
                    concurrencySemaphore.Release();
                }
            });
        }
    }
}

答案 2 :(得分:7)

解决方案可能是查看Microsoft here的预制代码。

描述如下:“提供一个任务调度程序,确保在ThreadPool之上运行时获得最大并发级别。”,并且就我能够测试它而言似乎可以做到这一点,在与ParallelOptions中的MaxDegreeOfParallelism属性相同。

答案 3 :(得分:6)

James

提供的C#等效样本
Action[] actionsArray = new Action[] {
new Action(() => DoComputation1()),
new Action(() => DoComputation2()),
    //...
new Action(() => DoComputation100())
  };

   System.Threading.Tasks.Parallel.Invoke(new Tasks.ParallelOptions {MaxDegreeOfParallelism =  5 }, actionsArray)

答案 4 :(得分:3)

简短回答:如果您想要的是限制工作任务的数量,以免他们不使您的网络服务饱和,那么我认为您的方法很好。

长答案: .NET 4.0中新的System.Threading.Tasks引擎在.NET ThreadPool之上运行。因为每个进程只有一个ThreadPool,默认最多250个工作线程。因此,如果您将ThreadPool的最大线程数设置为更适度的数字,则可以减少并发执行线程的数量,从而减少使用ThreadPool.SetMaxThreads (...) API的任务。

但是,请注意,您可能不会单独使用ThreadPool,因为您使用的许多其他类也可能将项目排队到ThreadPool。因此,您很可能会通过这样做最终削弱应用程序的其余部分。还要注意,因为ThreadPool使用一种算法来优化其对给定机器底层内核的使用,所以限制线程池可以排队到任意低数量的线程数可能会导致一些非常灾难性的性能问题。

同样,如果你想执行少量的工作任务/线程来执行某项任务,那么只创建少量任务(相对于100)是最好的方法。

答案 5 :(得分:3)

My blog post显示了如何使用“任务”和“操作”执行此操作,并提供了一个示例项目,您可以下载并运行该项目以查看两者的实际操作。

使用操作

如果使用Actions,则可以使用内置的.Net Parallel.Invoke函数。在这里,我们将其限制为最多并行运行5个线程。

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

var options = new ParallelOptions {MaxDegreeOfParallelism = 5};
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);
        }
    }

然后创建任务列表并调用函数让它们运行,一次最多同时执行5次,你可以这样做:

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

答案 6 :(得分:0)

虽然你可以创建一个实现这种行为的TaskScheduler子类,但它看起来并不像。

答案 7 :(得分:-3)

如果您的程序使用webservices,则同时连接数将限制为ServicePointManager.DefaultConnectionLimit属性。如果你想要5个同时连接,使用Arrow_Raider的解决方案是不够的。您还应该增加ServicePointManager.DefaultConnectionLimit,因为它默认只有2个。