I have a simple collection which I’m looping through like this:
foreach (MyObject mo in myObjects)
{
myObject.RunAcync();
}
RunAsync executes code in a separate thread, using new Thread(()=>{ .. }).Start(), it’s not in my power to change the code of RunAsync. I need to limit the number of instances of myObject running concurrently to N (real numbers are 2..10). What is the efficient way to do that using .NET4 and c#?
If you can modify
RunAsync, with what we have now (.NET 4) and what’s imminent (now when you think about it, .NET 4.5), I would use the Task Parallel Library (TPL) and return some sort ofTaskobject fromRunAsync. You can then easily tell what is done and what is running, and use the built-in TPL load balancing to limit the number of running tasks. Alternatively, if you had a non-async version of the method, you could also use the TPL’s Parallel.ForEach to invoke the method and it would deal with load-balancing and run only enough of the methods at one time to avoid performance issues