Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ensure Task.Delay is more accurate?

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.

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?

like image 506
soapergem Avatar asked Jun 29 '15 22:06

soapergem


1 Answers

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.

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.

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.

like image 162
i3arnon Avatar answered Sep 22 '22 14:09

i3arnon