简体   繁体   English

ASP.NET C#Parallel.ForEach性能提升

[英]ASP.NET C# Parallel.ForEach performance gain

I have a ASP MVC Controller contacting a bunch of http-sites in a for-loop. 我有一个ASP MVC控制器在for循环中联系一堆http站点。 Like: 喜欢:

foreach(string provider in providers){
    // get data from asomehttp URL
}

This takes about 4 seconds to perform... 这大约需要4秒钟才能执行...

I've tried: 我试过了:

Parallel.ForEach(providers, (provider) => {
     // get data from some http URL
});

And i see NO performance gain at all! 而且我完全看不到性能提升!

Why is this? 为什么是这样?

The source collection is partitioned and the work is scheduled on multiple threads based on the system environment. 源集合已分区,并且根据系统环境在多个线程上安排了工作。 The more processors on the system, the faster the parallel method runs. 系统上的处理器越多,并行方法运行的速度就越快。 For some source collections, a sequential loop may be faster, depending on the size of the source, and the kind of work being performed . 对于某些源集合, 根据源的大小和所执行工作的种类,顺序循环可能会更快。 For more information about performance, see Potential Pitfalls in Data and Task Parallelism . 有关性能的更多信息,请参见数据和任务并行性中的潜在陷阱 Do Not Assume That Parallel Is Always Faster In certain cases a parallel loop might run slower than its sequential equivalent. 不要假设并行总是快的,在某些情况下,并行循环的运行可能比顺序运行的慢。 The basic rule of thumb is that parallel loops that have few iterations and fast user delegates are unlikely to speedup much. 基本的经验法则是,具有很少迭代和快速用户委托的并行循环不太可能加快速度。

When parallelizing any code, including loops, one important goal is to utilize the processors as much as possible without over parallelizing to the point where the overhead for parallel processing negates any performance benefits. 在并行化任何代码(包括循环)时,一个重要的目标是尽可能多地利用处理器,而不会过度并行化到并行处理的开销抵消任何性能优势的地步。 In this particular example ,only the outer loop is parallelized because there is not very much work performed in the inner loop. 在此特定示例中 ,仅并行化外循环,因为在内循环中执行的工作量不大。 The combination of a small amount of work and undesirable cache effects can result in performance degradation in nested parallel loops. 少量工作和不良缓存效果的结合会导致嵌套并行循环中的性能下降。 Therefore, parallelizing the outer loop only is the best way to maximize the benefits of concurrency on most systems. 因此,仅并行化外循环是使大多数系统上的并发效益最大化的最佳方法。

To answer your question , it depends on the size of the source and the kind of work being performed. 要回答您的问题,这取决于源的大小和正在执行的工作类型。

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

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