Reputation: 9926
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() );
}
}
Upvotes: 8
Views: 4663
Reputation: 236218
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);
}
Upvotes: 14
Reputation: 869
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
}
Upvotes: -1