【问题标题】:How to limit the number of threads for a certain region of code?如何限制某个代码区域的线程数?
【发布时间】:2013-04-30 13:35:50
【问题描述】:
foreach (var action in actions)
{
    Task.Factory.StartNew(action);
}

但是,如果我需要限制同时运行的操作数怎么办?我该怎么做?

【问题讨论】:

标签: c# multithreading asynchronous


【解决方案1】:

我真的很喜欢这里的微软解决方案http://msdn.microsoft.com/en-us/library/ee789351.aspx

一次只允许一个线程的示例用法:

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

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

考虑在您的操作中使用 BlockingCollection 和 GetConsumingEnumerable() 以获得相当干净的实现 http://msdn.microsoft.com/en-us/library/dd287186.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多