How can I insert a delay between a List of Task<int>?

自古美人都是妖i 提交于 2021-02-05 05:23:55

问题


I have a loop that creates 5 Tasks. How can I insert a Delay of 5 seconds between each Task. I don't know how to fit Task.Delay(5000) in there.

 var tasks = new List<Task<int>>();

 for (var i = 0; i < 5; i++)
 {  
      tasks.Add(ProcessQueueAsync());
 }

 await Task.WhenAll(tasks);

My ProcessQueAsync method calls a server, retrieves data and returns and int.

  private async Task<int> ProcessQueAsync()
  {
     var result = await CallToServer();
     return result.Count;
  }

回答1:


 for (var i = 0; i < 5; i++)
 {  
      tasks.Add(ProcessQueueAsync());
      await Task.Delay(5000);
 }

Or:

 for (var i = 0; i < 5; i++)
 {  
      await ProcessQueueAsync();
      await Task.Delay(5000);
 }

Depending on that you want.




回答2:


If you want the tasks to run one after the other, with a 5 second delay, you should perhaps look at Task.ContinueWith instead of using Task.WhenAll. This would allow you to run tasks in serial rather than in parallel.



来源:https://stackoverflow.com/questions/28996680/how-can-i-insert-a-delay-between-a-list-of-taskint

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!