简体   繁体   English

Parallel.ForEach,Task.Factory和N个线程

[英]Parallel.ForEach, Task.Factory and N threads

I know this has been asked and discussed before but still I think it is not clear what to use in this scenario. 我知道之前已经有人问过这个问题,但我仍然不知道在这种情况下该使用什么。

I need to make 100 calls against a web service that I know can process 16 requests at a time (not that it would fail if it gets more) 我需要针对一个我知道一次可以处理16个请求的Web服务进行100次调用(不是,如果获得更多请求,它将失败)

I think that Parallel.ForEach is for more low level CPU intensive calls - it will decide how many threads are best suited. 我认为Parallel.ForEach适用于更底层的CPU密集型调用-它将决定最适合多少线程。 Task.Factory uses the thread pool so there could be less than 16 threads (also more) Task.Factory使用线程池,因此线程数可能少于16(更多)

Off course I could write my own Thread Pool, but isn't there a more obvious choice for this scenario? 当然,我可以编写自己的线程池,但是在这种情况下没有更明显的选择吗?

I would use Parallel.ForEach but specify a ParallelOptions with MaxDegreeOfParallelism set to 16. That way you're giving a very clear indication of the degree of parallelism you want. 我会用Parallel.ForEach但指定ParallelOptionsMaxDegreeOfParallelism设置为16,你给你想要的并行度的非常明确地表明这种方式。

If you use Task.Factory I think it's reasonable to assume you will get more than 16 concurrent tasks, although if you use asynchronous IO you needn't have 16 concurrent threads anyway. 如果您使用Task.Factory我认为可以假设您获得16个以上的并发任务,尽管如果您使用异步IO,则无论如何都不需要16个并发线程

You might want to look at TPL Dataflow - I haven't looked specifically at how easily you can partition the consumers, but as it's aimed squarely at producer/consumer scenarios, I'd be surprised if you couldn't create 16 consumers, then just produce the 100 calls. 您可能想看一下TPL数据流 -我没有专门研究如何轻松划分使用者,但是由于它直接针对生产者/消费者方案,因此如果您无法创建16个使用者,我会感到惊讶。只需拨打100个电话。

Or of course you could create 16 threads all consuming the same BlockingCollection containing data for the 100 calls. 或者,当然,您可以创建全部使用相同BlockingCollection 16个线程,其中包含100个调用的数据。 That would guarantee the level of parallelism... 这样可以保证并行度。

Note that in order to actually make 16 calls at the same time to the same HTTP host, you may need to tweak the <connectionManagement> part of app.config. 请注意,为了实际在同一时间对同一HTTP主机同时进行16个调用,您可能需要调整app.config的<connectionManagement>部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM