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() );
}
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With