System.Threading.Tasks - 限制并发任务的数量 [英] System.Threading.Tasks - Limit the number of concurrent Tasks

查看:680
本文介绍了System.Threading.Tasks - 限制并发任务的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始看在.NET 4.0中新的System.Threading.Tasks善良,并想知道是否有支持任何版本的限制了同时运行的并发任务的数量,或如果此应人工处理

I have just started to look at the new "System.Threading.Tasks" goodness in .Net 4.0, and would like to know if there is any build in support for limiting the number of concurrent tasks that run at once, or if this should be manually handled.

EG:如果我需要调用的计算方法的100倍,是有办法来设置100个任务,但只有5同时执行?答案可能只是创建5个任务,叫Task.WaitAny,并创建一个新的任务,因为每个previous之一结束。我只是想确保我不会错过一招,如果有更好的方法来做到这一点。

E.G: If I need to call a calculation method 100 times, is there a way to set up 100 Tasks, but have only 5 execute simultaneously? The answer may just be to create 5 tasks, call Task.WaitAny, and create a new Task as each previous one finishes. I just want to make sure I am not missing a trick if there is a better way to do this.

基本上,有一个内置的方式做到这一点:

Basically, is there a built in way to do this:

Dim taskArray() = {New Task(Function() DoComputation1()),
                   New Task(Function() DoComputation2()),
                   ...
                   New Task(Function() DoComputation100())}

Dim maxConcurrentThreads As Integer = 5
RunAllTasks(taskArray, maxConcurrentThreads)

感谢您的帮助。

Thanks for any help.

推荐答案

我知道这几乎是一岁,但我已经找到了一个更简单的方法来做到这一点,所以我想我也有同感:

I know this is almost a year old, but I have found a much easier way to achieve this, so I thought I would share:

Dim actionsArray() As Action = 
     new Action(){
         New Action(Sub() DoComputation1()),
         New Action(Sub() DoComputation2()),
         ...
         New Action(Sub() DoComputation100())
      }

System.Threading.Tasks.Parallel.Invoke(New Tasks.ParallelOptions() With {.MaxDegreeOfParallelism = 5}, actionsArray)

瞧!

这篇关于System.Threading.Tasks - 限制并发任务的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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