【问题标题】:Limiting the number of simultaneously executing tasks限制同时执行任务的数量
【发布时间】:2017-04-28 11:03:22
【问题描述】:

考虑一下这是一个巨大的任务池:

var tasks = new Task[4]
    {
        Task.Factory.StartNew(() => DoSomething()),
        Task.Factory.StartNew(() => DoSomething()),
        Task.Factory.StartNew(() => DoSomething()),
        Task.Factory.StartNew(() => DoSomething()),
        Task.Factory.StartNew(() => DoSomething())
    };

Task.WaitAll(tasks);

如果我只想同时运行 3 个任务怎么办?我将如何在代码中实现它?

【问题讨论】:

  • 一般情况下,您可以将其留给 TPL 调度程序。你有充分的理由干涉吗?
  • 我大体上同意。但是,在我的具体用例中,需要处理节流。

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


【解决方案1】:

一个比 MSDN 版本简单的例子是使用 Parallel.Invoke 设置最大并行度:

Parallel.Invoke(
    new ParallelOptions() { MaxDegreeOfParallelism = 3 }, 
    () => DoSomething(), 
    () => DoSomething(),
    () => DoSomething(),
    () => DoSomething(),
    () => DoSomething());

Parallel.Invoke() 将阻塞,直到所有并行操作完成(这意味着除了 parallel.invoke 之外的任何代码都不会运行,直到它们全部完成)。如果这对您不起作用,那么您最终需要创建自己的任务计划程序,如 Daniel 链接的 MSDN 文章所示。

【讨论】:

  • 关于阻塞:该语句会一直阻塞直到所有任务完成,与MaxDegeree无关。
  • 对不起,如果这听起来是我的意思,你是 100% 正确的,我并不是说 maxdegreeofparallelism 是导致阻塞的原因 - 更新帖子以更清楚我的意思希望
【解决方案2】:

我在 MSDN 上找到了this example。我相信它实现了你想要实现的目标。

【讨论】:

    【解决方案3】:

    所以你想指定同时任务的数量。请注意,这是一个糟糕的设计理念——至少在大多数情况下,您应该让系统决定同时执行多少任务。当您使用Task.Factory.StartNew 方法以这种方式创建任务而无需附加参数时,它们意味着尽快(尽快)执行,因此您通常不应该明确指定同时执行的数量。

    在这种情况下,ASAP 是什么意思?任务管理器将决定是立即启动所有任务,还是直接启动其中一些任务,或者等待其他任务完成,等等。

    您可以使用某种手动同步来实现您的目标。我的意思是像一个信号量。 http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx

    如果你不需要做其他工作,只想等待任务完成,我更喜欢 Gary S 建议的Parallel.Invoke

    【讨论】:

    • 您是如何决定要尽快执行此类任务的?某种需求完全不可能需要其他东西?
    • 原因是你使用StartNew没有任何特殊参数。以这种方式创建的任务会尽快运行。我重写了我的答案以更清楚。
    【解决方案4】:

    My blog post 展示了如何使用 Tasks 和 Actions 执行此操作,并提供了一个示例项目,您可以下载并运行以查看两者的实际效果。

    原发帖者并没有具体说明他们更喜欢使用 Actions 还是 Tasks,而且有时从一个切换到另一个并不容易,所以我在这里介绍两种解决方案。

    有动作

    如果使用 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 2018-05-25
      • 2018-10-26
      • 1970-01-01
      相关资源
      最近更新 更多