0

I'm using Task.WhenAll on a collection of Task HttpResponseMessage. I want to add a Task.Delay between each request to rate limit the calls to the API.

Obviously my list is a strongly typed List of Task<HttpResponseMessage> and a Task.Delay is just a Task. Is there a way to make this handle both or do I need to rethink my implementation?

          foreach (var x in items)
            {
                requestList.Add(MakeHttpClientCall(x)); <== requestList = List<Task<HttpResponseMessage>>

              // want to add a Task.Delay here e.g.
                requestList.Add(Task.Delay(4)) etc
            }


            Task allTasks = Task.WhenAll(statNumberList);
            try
            {

                await allTasks;

            }

I've tried playing around with lists of Task and casting but no luck so far. Hope this makes sense! Thanks

Michael Harper
  • 1,531
  • 2
  • 25
  • 42
  • 2
    You can execute tasks from `requestList` in a loop and insert a timeout between executions, like it shown in the existing thread [How can I insert a delay between a List of Task?](https://stackoverflow.com/questions/28996680/how-can-i-insert-a-delay-between-a-list-of-taskint) – Pavel Anikhouski Apr 19 '20 at 13:41
  • Currently your delay tasks do not delay HttpClient requests. Each delay is executed as a separate task without adding a delay to HttpClient requests. If you use solution from the thread provided by Pavel Anikhouski then your problem with different task types will disappear. – Iliar Turdushev Apr 19 '20 at 16:09
  • Another option you could consider, instead of introducing a rate limit, is to introduce a [concurrency limit](https://stackoverflow.com/questions/10806951/how-to-limit-the-amount-of-concurrent-async-i-o-operations). – Theodor Zoulias Apr 19 '20 at 16:55
  • Thanks guys I'll look into those options – Michael Harper Apr 19 '20 at 17:26

0 Answers0