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?
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.
I found this example on MSDN. I believe it implements what you are trying to accomplish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With