异步执行限制并发实例数 [英] Async execution limiting the number of concurrent instances
问题描述
我有一个简单的集合,我这样循环:
foreach(MyObject mo in myObjects)
{
myObject.RunAcync();
}
RunAsync
在单独的线程中,使用 new Thread(()=> {..})。Start()
,不能更改< $ c> RunAsync 。我需要限制 myObject
同时运行到N(实数为2..10)的实例数。使用 .NET4
和 c#
?
的有效方法是什么如果你可以修改
RunAsync
,我们现在有什么(.NET 4)和什么是迫在眉睫的你会想到它,.NET 4.5),我会使用任务并行库(TPL)并从 RunAsync返回某种类型的任务
code>。然后,您可以轻松地知道所做的和正在运行的内容,并使用内置的TPL负载平衡来限制正在运行的任务的数量。或者,如果您有非异步版本的方法,您还可以使用TPL的 Parallel.ForEach 调用该方法,它将处理负载均衡,并一次只运行足够的方法以避免性能问题
I have a simple collection which I'm looping through like this:
foreach (MyObject mo in myObjects)
{
myObject.RunAcync();
}
RunAsync
executes code in a separate thread, using new Thread(()=>{ .. }).Start()
, it's not in my power to change the code of RunAsync
. I need to limit the number of instances of myObject
running concurrently to N (real numbers are 2..10). What is the efficient way to do that using .NET4
and c#
?
解决方案 If you can modify RunAsync
, with what we have now (.NET 4) and what's imminent (now when you think about it, .NET 4.5), I would use the Task Parallel Library (TPL) and return some sort of Task
object from RunAsync
. You can then easily tell what is done and what is running, and use the built-in TPL load balancing to limit the number of running tasks. Alternatively, if you had a non-async version of the method, you could also use the TPL's Parallel.ForEach to invoke the method and it would deal with load-balancing and run only enough of the methods at one time to avoid performance issues
这篇关于异步执行限制并发实例数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!