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

查看:24
本文介绍了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.

E.G:如果我需要调用一个计算方法 100 次,有没有办法设置 100 个任务,但只有 5 个同时执行?答案可能只是创建 5 个任务,调用 Task.WaitAny,并在前一个任务完成时创建一个新任务.如果有更好的方法可以做到这一点,我只是想确保我不会错过任何技巧.

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)

感谢您的帮助.

推荐答案

我知道这已经快一年了,但我找到了一个更简单的方法来实现这一点,所以我想我会分享:

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天全站免登陆