简体   繁体   English

如何限制通过并行任务库运行的活动任务的数量?

[英]How to limit the number of active Tasks running via the Parallel Task Library?

I have some ConcurrentQueue that contain Action ( System.Action ). 我有一些包含Action(System.Action)的ConcurrentQueue。 Each action in this queue need to run ( need to be called by using invoke ). 需要运行此队列中的每个操作(需要使用invoke调用)。

When the queue is not empty => the action need to be invoke => But i want to make some limit on the number of the parallel task that will run. 当队列不为空时=>需要调用动作=>但是我想对将要运行的并行任务的数量进行一些限制。 Beside this, A new action can be added to the queue any time. 除此之外,可以随时向队列添加新动作。

How to do it ? 怎么做 ?

( using .net 4.0 ) (使用.net 4.0)

I wrote something but i not sure this is the best approach 我写了一些东西,但我不确定这是最好的方法

 SemaphoreSlim maxThread = new SemaphoreSlim(5);

 while( !actionQueue.IsEmpty )
        {
            maxThread.Wait();
            Task.Factory.StartNew( () =>
            {
                Action action;
                if( actionExecution.TryDequeue( out action) )
                {
                    action.Invoke();
                }
            },
            TaskCreationOptions.LongRunning ).ContinueWith( ( task ) => maxThread.Release() );
        }
    }

Take a look on MSDN article How to: Create a Task Scheduler That Limits Concurrency . 查看MSDN文章如何:创建限制并发的任务计划程序 You can use LimitedConcurrencyLevelTaskScheduler implementation from it to make your code like this: 您可以使用它的LimitedConcurrencyLevelTaskScheduler实现来生成如下代码:

var scheduler = new LimitedConcurrencyLevelTaskScheduler(5);
TaskFactory factory = new TaskFactory(scheduler);

while( !actionQueue.IsEmpty )
{
    factory.StartNew( () =>
    {
        Action action;
        if(actionExecution.TryDequeue(out action))                
            action.Invoke();

    }, TaskCreationOptions.LongRunning);
}

You will need to specify ParallelOptions 您需要指定ParallelOptions

ParallelOptions options = new ParallelOptions();
options.MaxDegreeOfParallelism = 4;//value of your choice

if (Parallel.ForEach(PDFFiles, options, element =>
{
   //do work 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM