Shaamaan's answer is good and probably the one you want to use for your specific scenario. I just present a couple of other possible options that you could use, and this may be more applicable to other situations.
My blog post shows how to do this with both tasks and actions, and provides an example project that you can download and run to see both In battle.
With action
When using actions, you can use the built-in .Net Parallel.Invoke function. Here we restrict it to running no more than 10 threads in parallel.
var listOfActions = new List<Action>(); for (int i = 0; i < 10000; i++) { // Note that we create the Action here, but do not start it. listOfActions.Add(() => DoSomething()); } var options = new ParallelOptions {MaxDegreeOfParallelism = 10}; Parallel.Invoke(options, listOfActions.ToArray());
With tasks
There is no built-in function with Jobs. However, you can use the one I provide on my blog.
And then, by creating your list of tasks and calling the function so that they start, and, for example, no more than 10 simultaneous, you can do this:
var listOfTasks = new List<Task>(); for (int i = 0; i < 10000; i++) { var count = i; // Note that we create the Task here, but do not start it. listOfTasks.Add(new Task(() => Something())); } Tasks.StartAndWaitAllThrottled(listOfTasks, 10);
source share