如何获得可等待的 Thread.Sleep? [英] How to get awaitable Thread.Sleep?

查看:8
本文介绍了如何获得可等待的 Thread.Sleep?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个基于 await/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.

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

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.

我应该用什么替换Thread.Sleep(10000)来达到和

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

await Thread.SleepAsync(10000)

?

更新

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

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

推荐答案

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

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 不需要新线程,并且正是为此目的而设计的:

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

这篇关于如何获得可等待的 Thread.Sleep?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆