How to limit the number of active Tasks running vi

2019-03-19 19:24发布

I have some ConcurrentQueue that contain Action ( System.Action ). Each action in this queue need to run ( need to be called by using 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 )

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

2条回答
Evening l夕情丶
2楼-- · 2019-03-19 19:53

Take a look on MSDN article How to: Create a Task Scheduler That Limits Concurrency. You can use LimitedConcurrencyLevelTaskScheduler implementation from it to make your code like this:

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);
}
查看更多
Rolldiameter
3楼-- · 2019-03-19 20:09

You will need to specify ParallelOptions

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

if (Parallel.ForEach(PDFFiles, options, element =>
{
   //do work 
}
查看更多
登录 后发表回答