8

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() ); } } 
4
  • 2
    Can you explain the real problem? Why do you feel the need to limit the number of tasks? Commented Jul 16, 2013 at 10:34
  • just academic experience .. i want to learn. but i also want to know why i don't need to make this limit ? Commented Jul 16, 2013 at 10:39
  • 1
    There is no need to limit the number of tasks - I see now you're talking about concurrently executing tasks and not the total number in the queue; lazyberezovsky's answer below is the correct one for this scenario. Commented Jul 16, 2013 at 10:50
  • 2
    Take a look at TPL dataflow, depending on you're scenario it can act like a great fit. msdn.microsoft.com/en-us/library/hh228603.aspx Commented Jul 16, 2013 at 10:55

2 Answers 2

14

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); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Why is this better than the solution that the OP suggested using SemaphoreSlim?
-1

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 } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.