触发Parallel.For in c#with sleep

时间:2016-12-06 10:59:28

标签: c# asp.net asp.net-mvc parallel-processing sleep

我有一个Parallel.For循环,当我发生这样的计划任务时,我会在某个时刻执行大量的HTTP请求:

 Parallel.For(0, doc.GetElementsByTagName("ItemID").Count, i => {
 var xmlResponse =    PerformHttpRequestMethod(); 
 });

有没有办法让我在计数器值达到2,4,6,8,10之后设置循环暂停等等......

所以每2个方法调用它执行,睡2分钟让我们说..

有什么办法可以实现这个目标吗?

3 个答案:

答案 0 :(得分:2)

我建议您使用Task.Delay

现在,您的方法asyncronous使用async/await

public async Task DoSomething()
{
   int i = 0;
   while (i < doc.GetElementsByTagName("ItemID").Count)
   {
       Task.Run(() => PerformHttpRequestMethod());
       if(i%2==0){
           await Task.Delay(TimeSpan.FromMinutes(2));
           //or simply: 
           await Task.Delay(120000);//120000 represents 2 minutes.
       }
       i++;
    }
}

或者只是想要使用for循环。

public async Task DoSomething()
{
    for (int i = 0; i < doc.GetElementsByTagName("ItemID").Count; i++)
    {
        Task.Run(() => PerformHttpRequestMethod());
        if(i%2==0){
            await Task.Delay(TimeSpan.FromMinutes(2));
        }
    }
}
  

如果我想要从0到4进行迭代然后再睡5到9,那么第二个例子怎么样呢?

public async Task DoSomething()
{
    for (int i = 0; i < doc.GetElementsByTagName("ItemID").Count; i=i+5)
    {
        if( i%10 == 0 ){
           for( int j=i;j<=i+4;j++){                   
              Task.Run(() => PerformHttpRequestMethod());
           }
        }
        else{
           for(int j=i;j<=i+4;j++){
              await Task.Delay(TimeSpan.FromMinutes(2));
           }
        }
    }
}

让我们测试算法的正确性。

i=0 - &gt; (0%10 == 0 - &gt; true),然后执行Task.Run(() => PerformHttpRequestMethod()) i =(0,4)

i=5 - &gt; (5%10 == 0 - &gt; false),然后执行await Task.Delay(TimeSpan.FromMinutes(2));因为i =(5,9)。

等等......

答案 1 :(得分:2)

我真的没有看到使用Parallel.For的意义,如果你想要每隔一次迭代睡眠x分钟或几秒钟......那么使用普通的for for循环怎么样?:

for(int i = 0; i < doc.GetElementsByTagName("ItemID").Count; ++i)
{
    var xmlResponse = PerformHttpRequestMethod();
    if (i % 2 == 0)
    {
      System.Threading.Thread.Sleep(TimeSpan.FromMinutes(2));
    }
}

或许你想跟踪目前正在进行的迭代次数?:

int inFlight = 0;
Parallel.For(0, doc.GetElementsByTagName("ItemID").Count, i => {
  System.Threading.Interlocked.Increment(ref inFlight);
  if (inFlight % 2 == 0)
   System.Threading.Thread.Sleep(TimeSpan.FromMinutes(2));

  var xmlResponse = PerformHttpRequestMethod();
  System.Threading.Interlocked.Decrement(ref inFlight);
});

答案 2 :(得分:0)

你可以通过组合一个Parallel.For和一个普通for循环来做到这一点:

for(var i = 0;i<doc.GetElementsByTagName("ItemID").Count;i = i+2)
{
    Parallel.For(0, 2, i => {
        var xmlResponse =    PerformHttpRequestMethod(); 
    });
    Thread.Sleep(2000);
}