Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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() );
        }
    }
like image 590
Yanshof Avatar asked Jul 16 '13 10:07

Yanshof


1 Answers

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);
}
like image 158
Sergey Berezovskiy Avatar answered Nov 16 '22 02:11

Sergey Berezovskiy