并行ForEach在生成之前等待500毫秒 [英] Parallel ForEach wait 500 ms before spawning

查看:53
本文介绍了并行ForEach在生成之前等待500毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种情况:

var tasks = new List<ITask> ...
Parallel.ForEach(tasks, currentTask => currentTask.Execute() );

是否可以指示PLinq等待500ms,直到产生下一个线程?

Is it possible to instruct PLinq to wait for 500ms before the next thread is spawned?

System.Threading.Thread.Sleep(5000);

推荐答案

您正在使用 Parallel.Foreach 完全错误,您应该制作一个特殊的枚举器,将其速率限制为每500毫秒获取一次数据

You are using Parallel.Foreach totally wrong, You should make a special Enumerator that rate limits itself to getting data once every 500 ms.

由于您未提供任何详细信息,因此我对您的 DTO 的工作方式进行了一些假设.

I made some assumptions on how your DTO works due to you not providing any details.

private IEnumerator<SomeResource> GetRateLimitedResource()
{
    SomeResource someResource = null;
    do
    {
        someResource = _remoteProvider.GetData();

        if(someResource != null)
        {
             yield return someResource;
             Thread.Sleep(500);
        }
    } while (someResource != null);
}

这就是您的并购外观

Parallel.ForEach(GetRateLimitedResource(), SomeFunctionToProcessSomeResource);

这篇关于并行ForEach在生成之前等待500毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆