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

我有一些包含Action(System.Action)的ConcurrentQueue。 需要运行此队列中的每个操作(需要使用invoke调用)。

当队列不为空时=>动作需要调用=>但是我想对将要运行的并行任务的数量进行一些限制。 除此之外,可以随时向队列添加新动作。

怎么做 ?

(使用.net 4.0)

我写了一些东西,但我不确定这是最好的方法

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() ); } } 

看看MSDN文章如何:创建限制并发的任务计划程序 。 您可以使用它的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); } 

您需要指定ParallelOptions

 ParallelOptions options = new ParallelOptions(); options.MaxDegreeOfParallelism = 4;//value of your choice if (Parallel.ForEach(PDFFiles, options, element => { //do work }