简体   繁体   English

Parallel.ForEach中的C#延迟

[英]C# delay in Parallel.ForEach

I use 2 Parallel.ForEach nested loops to retrieve information quickly from a url. 我使用2个Parallel.ForEach嵌套循环从URL中快速检索信息。 This is the code: 这是代码:

while (searches.Count > 0)
{
    Parallel.ForEach(searches, (search, loopState) =>
        {
            Parallel.ForEach(search.items, item =>
                {
                    RetrieveInfo(item);
                }
            );
        }
    );
}

The outer ForEach has a list of, for example 10, whilst the inner ForEach has a list of 5. This means that I'm going to query the url 50 times, however I query it 5 times simultaneously (inner ForEach ). 外部ForEach的列表为10,而内部ForEach的列表为5。这意味着我将查询该URL 50次,但是同时查询5次(内部ForEach )。

I need to add a delay for the inner loop so that after it queries the url, it waits for x seconds - the time taken for the inner loop to complete the 5 requests. 我需要为内部循环添加一个延迟,以便在查询url之后,它等待x秒-内部循环完成5个请求所花费的时间。

Using Thread.Sleep is not a good idea because it will block the complete thread and possibly the other parallel tasks. 使用Thread.Sleep并不是一个好主意,因为它将阻塞整个线程,并可能阻塞其他并行任务。

Is there an alternative that might work? 有没有可行的替代方案?

To my understanding, you have 50 tasks and you wish to process 5 of them at a time. 据我了解,您有50个任务,并且希望一次处理5个任务。

If so, you should look into ParallelOptions.MaxDegreeOfParallelism to process 50 tasks with a maximum degree of parallelism at 5. When one task stops, another task is permitted to start. 如果是这样,您应该查看ParallelOptions.MaxDegreeOfParallelism以处理最大并行度为5的50个任务。当一个任务停止时,允许另一个任务开始。

If you wish to have tasks processed in chunks of five, followed by another chunk of five (as in, you wish to process chunks in serial), then you would want code similar to 如果您希望以五个为一组来处理任务,然后以五个为一组来处理任务(例如,希望串行处理),那么您将需要类似于

for(...)
{
   Parallel.ForEach(
      [paralleloptions,]
      set of 5, action
   )
}

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

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