How to get awaitable Thread.Sleep?

C#.NetMultithreadingAsync Await

C# Problem Overview


I'm writing a network-bound application based on await/sleep paradigm.

Sometimes, connection errors happen, and in my experience it pays to wait for some time and then retry operation again.

The problem is that if I use Thread.Sleep or another similar blocking operation in await/async, it blocks all activity in the caller thread.

What should I replace Thread.Sleep(10000) with to achieve the same effect as

await Thread.SleepAsync(10000)

?

UPDATE

I'll prefer an answer which does this without creating any additional thread

C# Solutions


Solution 1 - C#

The other answers suggesting starting a new thread are a bad idea - there's no need to do that at all. Part of the point of async/await is to reduce the number of threads your application needs.

You should instead use Task.Delay which doesn't require a new thread, and was designed precisely for this purpose:

// Execution of the async method will continue one second later, but without
// blocking.
await Task.Delay(1000);

This solution also has the advantage of allowing cancellation, if a cancellation token is provided. Example:

public async Task DoWork(CancellationToken token)
{
	await Task.Delay(1000, token);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArsen ZahrayView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow