Task based processing with a limit for concurrent task number with .NET 4.5 and c#

不羁的心 提交于 2019-12-25 06:59:32

问题


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

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

The task:

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

回答1:


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.



来源:https://stackoverflow.com/questions/12366608/task-based-processing-with-a-limit-for-concurrent-task-number-with-net-4-5-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!