Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting the number of simultaneously executing tasks

Consider this a huge pool of tasks:

var tasks = new Task[4]
    {
        Task.Factory.StartNew(() => DoSomething()),
        Task.Factory.StartNew(() => DoSomething()),
        Task.Factory.StartNew(() => DoSomething()),
        Task.Factory.StartNew(() => DoSomething()),
        Task.Factory.StartNew(() => DoSomething())
    };

Task.WaitAll(tasks);

What if I only wanted to run say 3 tasks simultaneously? How would I implement that in code?

like image 510
Kjensen Avatar asked Oct 15 '11 00:10

Kjensen


2 Answers

A less complicated example than the MSDN version would be to use Parallel.Invoke setting the max degree of parallelism:

Parallel.Invoke(
    new ParallelOptions() { MaxDegreeOfParallelism = 3 }, 
    () => DoSomething(), 
    () => DoSomething(),
    () => DoSomething(),
    () => DoSomething(),
    () => DoSomething());

Parallel.Invoke() will however block until all parallel operations are finished (meaning that no code beyond the parallel.invoke will run until they are all completed). If this doesn't work for you then you will end up needing to create your own task scheduler as is shown is the MSDN article linked by Daniel.

like image 129
Gary.S Avatar answered Nov 07 '22 22:11

Gary.S


I found this example on MSDN. I believe it implements what you are trying to accomplish.

like image 39
Daniel Pratt Avatar answered Nov 07 '22 23:11

Daniel Pratt