基于任务的处理,使用 .NET 4.5 和 C# 限制并发任务数 [英] Task based processing with a limit for concurrent task number with .NET 4.5 and c#

查看:38
本文介绍了基于任务的处理,使用 .NET 4.5 和 C# 限制并发任务数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按照这个,任何人都可以针对以下任务发布准系统解决方案,针对 .NET 4.5(以及更大规模的 WPF UI)?

Following this, could anyone post a barebone solution for the following task, targeting .NET 4.5 (and WPF UI on a bigger scale)?

基本上,我正在寻找在 .NET 4.5 和 c# 上实现的任何 Torrent 应用程序的功能模拟.

Basically I'm looking for a functional analog of any torrent application implemented on .NET 4.5 and c#.

任务:

我有IEnumerable,包含1000个IProcessable的实例,IProcessableProcess(int argument) 方法,执行需要 1 到 10 秒.我想遍历集合并处理 IProcessable 的每个实例,将并发处理的实例数限制为 N (1..10),最大并发实例数应该很容易调整.理想情况下,我会让每个 IProcessable 报告 Process 完成的进度,这里是 Process 的原型(它可能需要转换为某些东西而不是 void 以启用进度报告):

I have IEnumerable<IProcessable>, containing 1000 instances of IProcessable, IProcessable has Process(int argument) method, taking from 1 to 10 seconds to execute. I want to loop through the collection and process each instance of IProcessable, limiting the number of concurrently processed instances to N (1..10), number of max concurrent instances should be easily adjustable. Ideally I'd each IProcessable to report about the progress of Process completion, here's a prototype of Process (it probably needs to be converted to something rather than void in order to enable progress reporting):

void Process(int e)
{
   int progress = 0;
   ...Sleep for 100ms;
   int progress = 30;
   ...Sleep for 100ms;
   int progress = 50;
   ...
}

推荐答案

如果你只想限制一次处理的实例数量,看起来像 Parallel.ForEach() 将是一个很好的解决方案.使用时可以指定MaxDegreeOfParallelism,就是这样做的.

If all you want is to limit the number processed instances at a time, it seems like Parallel.ForEach() would be a good solution. When you use it, you can specify MaxDegreeOfParallelism, which does that.

这篇关于基于任务的处理,使用 .NET 4.5 和 C# 限制并发任务数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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