如何限制特定代码区域的线程数? [英] How to limit the number of threads for a certain region of code?

查看:35
本文介绍了如何限制特定代码区域的线程数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

推荐答案

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

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
 });

考虑在操作中使用BlockingCollection和GetConsumingEnumerable()以获得非常干净的实现http://msdn.microsoft.com/zh-CN/library/dd287186.aspx

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

这篇关于如何限制特定代码区域的线程数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆