简体   繁体   English

如何获得可等待的 Thread.Sleep?

[英]How to get awaitable Thread.Sleep?

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.问题是,如果我在 await/async 中使用 Thread.Sleep 或其他类似的阻塞操作,它会阻塞调用者线程中的所有活动。

What should I replace Thread.Sleep(10000) with to achieve the same effect as我应该用什么替换 Thread.Sleep(10000) 以达到与

await Thread.SleepAsync(10000)

? ?

UPDATE更新

I'll prefer an answer which does this without creating any additional thread我更喜欢在不创建任何额外线程的情况下执行此操作的答案

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. async / await的部分目的是减少应用程序所需的线程数。

You should instead use Task.Delay which doesn't require a new thread, and was designed precisely for this purpose:您应该改用不需要新线程的Task.Delay ,并且正是为此目的而设计的:

// 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM