How can I await a minimum amount of time?

  • A+

I have an async C# method where I am getting an HTTP resource, and I am doing it in an infinite loop. However I don't want to hit the resource too quickly. My current code is:

HttpClient http = new HttpClient(); while (true) {     // Long-poll the API     var response = await http.GetAsync(buildUri());      Console.WriteLine("Resp: " + response.ToString());     Console.WriteLine("CONTENT:");     Console.WriteLine(await response.Content.ReadAsStringAsync()); } 

However, I want to be able to make sure I don't make an HTTP request more often than once per 10 seconds. So I want to start a 10 second timer at the beginning of the loop, and at the end say "await the completion of the 10 second timer". Is there a way to do this in C#.NET?


At the simplest:

while (true) {     var rateLimit = Task.Delay(TimeSpan.FromSeconds(10));     // ...await your http/whatever     await rateLimit; } 

The await rateLimit will complete immediately if the http work took over the 10 seconds.

However, you may choose to compare the times before and after the http work, to see if you even need to wait; more like:

while (true) {     var timeBefore = ...     // ...await your http/whatever     var timeAfter = ...     // ... calculate time left     if (timeLeft > TimeSpan.Zero) await Task.Delay(timeLeft); } 

This avoids the plumbing needed for Task.Delay in the scenarios where it would complete immediately.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: