如何确保Task.Delay更准确? [英] How can I ensure Task.Delay is more accurate?

查看:391
本文介绍了如何确保Task.Delay更准确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WPF应用程序,它广泛使用awaitasync方法.我在几个地方叫await Task.Delay(...);来插入暂停.但是我遇到的麻烦是,尽管这些暂停中的许多暂停都可以,但是在某些地方我绝对需要暂停才能精确.因此,换句话说,如果我调用await Task.Delay(2000);,则在我的应用程序中有一些地方需要保证它只会暂停2秒(而不是2.2秒以上).

I've got a WPF application which makes use of await and async methods extensively. There are several places where I call await Task.Delay(...); to insert pauses. But the trouble I'm running into is that while many of these pauses are fine to be a little bit off, there are some places where I absolutely need the pause to be precise. So in other words if I call await Task.Delay(2000); there are some places in my application where I need to guarantee that it's only going to pause for 2 seconds (and not 2.2+ seconds).

我相信麻烦来自这样一个事实:我确实有许多不同的异步方法,因此当我告诉其中一个延迟时,线程池中应该返回的线程不足活着,这会无意中导致比预期更长的延迟.

I believe the trouble comes from the fact that I do have so many different async methods, so that when I tell one of them to delay, there aren't enough threads left in the thread pool right when it's supposed to come back alive, which results, inadvertently, in longer delays than intended.

当您有业务需要尽可能准确地延迟时,用于线程的C#最佳实践"是什么?显然,仅靠异步方法似乎还不够(尽管它们很容易阅读).我应该手动创建一个具有更高优先级的线程并使用Thread.Sleep吗?是否增加线程池中的线程数?我要使用BackgroundWorker吗?

What are the C# "best practices" for threading when you have a business need for your delays to be as accurate as possible? Clearly it doesn't seem like async methods are enough on their own (even though they are nice to read). Should I manually create a thread with a higher priority and use Thread.Sleep? Do I up the number of threads in the thread pool? Do I use a BackgroundWorker?

推荐答案

您不能真正使Task.Delay本身更加准确,因为它基于内部Threading.Timer,其分辨率最高为15毫秒,并安排了回调到线程池需要花费时间.

You can't really make Task.Delay itself more accurate as it's based on an internal Threading.Timer which has a resolution of up to 15 ms and scheduling the callback to the thread pool takes its time.

如果您确实需要准确,则需要一个专用线程.您可以使用Thread.Sleep将其睡眠2秒钟,然后在唤醒时执行您需要做的事情.

If you really need to be accurate you need a dedicated thread. You can have it sleep for 2 seconds with Thread.Sleep and when it wakes up do what you need to do.

由于Thread.Sleep导致上下文切换,线程从该线程移出CPU,所以更准确的选择是执行忙碌等待" (例如,使用while循环) .这样可以省去将上下文切换回CPU的成本,而这会花费一些时间.

Since Thread.Sleep causes a context-switch where the thread goes out of the CPU an even more accurate option would be to do a "busy wait" (e.g. with a while loop). That will remove the cost of the context-switch back to the CPU which takes some time.

您应该意识到,尽管这些选项需要太多资源,但您应该考虑这是否真的必要.

You should realize though that these options require too much resources and you should consider whether that's really necessary.

这篇关于如何确保Task.Delay更准确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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