Vladimir Arkhangelskii
Vladimir Arkhangelskii

Reputation: 120

Delay an operation within a while loop in ASP.NET (async)

I need to create a while loop with 10 seconds of delay between each iteration:

while (true)
{
    // operation
    // delay for 10 seconds
}

Upvotes: 1

Views: 2531

Answers (2)

Tobias Tengler
Tobias Tengler

Reputation: 7454

You could use Task.Delay for this:

var timespan = TimeSpan.FromSeconds(10); 

await Task.Delay(timespan);

// or

Task.Delay(timespan).Wait();

I'm recommending this over Thread.Sleep, since Thread.Sleep blocks your entire Thread while waiting, whilst Task.Delay allows the Thread to deal with other work, while waiting.

Upvotes: 7

kd2amc
kd2amc

Reputation: 39

Just insert a sleep timer inside the while loop that sleeps for 10 seconds.

See this thread: How do I get my C# program to sleep for 50 msec?

Upvotes: 0

Related Questions