Task based processing with a limit for concurrent

2019-09-12 06:14发布

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条回答
聊天终结者
2楼-- · 2019-09-12 07:18

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.

查看更多
登录 后发表回答