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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13429707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:32:14  来源:igfitidea点击:

How to get awaitable Thread.Sleep?

c#.netmultithreadingasync-await

提问by Arsen Zahray

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

我更喜欢一个不创建任何额外线程的答案

采纳答案by Jon Skeet

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/awaitis to reducethe number of threads your application needs.

建议开始一个新线程的其他答案是一个坏主意 - 根本没有必要这样做。点的一部分async/await减少线程应用程序需要的数量。

You should instead use Task.Delaywhich doesn'trequire 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);