x2bool
x2bool

Reputation: 2906

How to limit the number of threads for a certain region of code?

foreach (var action in actions)
{
    Task.Factory.StartNew(action);
}

But, what if I need to limit the number of actions that run in the same time? How do I do that?

Upvotes: 0

Views: 119

Answers (1)

Jras
Jras

Reputation: 518

I really like microsoft's solution here http://msdn.microsoft.com/en-us/library/ee789351.aspx.

Example usage for only allowing one thread at a time:

 LimitedConcurrencyLevelTaskScheduler lcts = new LimitedConcurrencyLevelTaskScheduler(1);
 TaskFactory factory = new TaskFactory(lcts);

 factory.StartNew(()=> 
 {
   //work as usual
 });

consider using a BlockingCollection and GetConsumingEnumerable() inside your action for a pretty clean implementation http://msdn.microsoft.com/en-us/library/dd287186.aspx

Upvotes: 1

Related Questions