我在写基于计谋/睡眠模式的网络结合的应用。
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 than retry operation again.
现在的问题是,如果我使用了Thread.Sleep或一些类似的阻塞操作计谋/异步,在调用者的线程阻塞所有活动。
The problem is that if I use Thread.Sleep or some similar blocking operation in await/async, it blocks all activity in the caller thread.
我应该更换了Thread.Sleep(10000)一起acheave相同的效果
What should I replace Thread.Sleep(10000) with to acheave the same effect as
await Thread.SleepAsync(10000)
更新
我会preFER它做到这一点不会造成任何额外的线程的答案
I'll prefer an answer which does this without creating any additional threads
其他答案建议启动一个新的线程是一个坏主意 - 有没有必要做,在所有。部分点的异步
/ 等待
是减少的线程数您的应用程序需要。
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.
您应该使用Task.Delay其中的不的需要一个新的线程,并且被设计precisely为了这个目的:
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);