System.Threading.Tasks - Limit the number of concurrent Tasks System.Threading.Tasks - Limit the number of concurrent Tasks multithreading multithreading

System.Threading.Tasks - Limit the number of concurrent Tasks


I know this is almost a year old, but I have found a much easier way to achieve this, so I thought I would share:

Dim actionsArray() As Action =      new Action(){         New Action(Sub() DoComputation1()),         New Action(Sub() DoComputation2()),         ...         New Action(Sub() DoComputation100())      }System.Threading.Tasks.Parallel.Invoke(New Tasks.ParallelOptions() With {.MaxDegreeOfParallelism = 5}, actionsArray)

Voila!


I know this is an old thread, but I just wanted to share my solution to this problem: use semaphores.

(This is in C#)

private void RunAllActions(IEnumerable<Action> actions, int maxConcurrency){    using(SemaphoreSlim concurrencySemaphore = new SemaphoreSlim(maxConcurrency))    {        foreach(Action action in actions)        {            Task.Factory.StartNew(() =>            {                concurrencySemaphore.Wait();                try                {                    action();                }                finally                {                    concurrencySemaphore.Release();                }            });        }    }}


A solution might be to take a look at the pre-made code from Microsoft here.

The description goes like this: "Provides a task scheduler that ensures a maximum concurrency level while running on top of the ThreadPool.", and as far as I've been able to test it seems to do the trick, in the same manner as the MaxDegreeOfParallelism property in ParallelOptions.