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

查看:175
本文介绍了如何获得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 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.

您应该使用<一个href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.delay.aspx"><$c$c>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);

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

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