198

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

KumarAnkit
  • 713
  • 1
  • 9
  • 26
Arsen Zahray
  • 24,367
  • 48
  • 131
  • 224

1 Answers1

452

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);
}
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I'm still coming to grips with the a4.5 stuff. Where's the branch of execution on the code after that statement? Does the non-sleeping/blocking portion execute it or the 'thread' that waits? Does the main non-blocking execution just leave the block following (aka return)? – kenny Nov 17 '12 at 12:12
  • 2
    @kenny: You may find my [`async` intro](http://nitoprograms.blogspot.com/2012/02/async-and-await.html) helpful. When the awaitable returned by `Task.Delay` is `await`ed, since it's not complete, the current method returns an incomplete task. Later, when the `Delay` completes (off a timer, not a thread), the remainder of the method is scheduled to run. The continuation runs in a "context" which *may* return to the same original thread - details on my blog. – Stephen Cleary Nov 17 '12 at 13:53
  • @StephenCleary thanks for that. So am I right in saying that the code after await is 'scheduled' for execution and the calling thread returns? – kenny Nov 18 '12 at 13:29
  • 4
    Yes, the calling thread returns (immediately) and the code after the `await` is scheduled (eventually). – Stephen Cleary Nov 18 '12 at 13:31