I need a solution to perform arbitrary pause. The delay accuracy is irrelevant. What is the practical difference in such scenario between WaitHandle.WaitOne Method (TimeSpan) and Thread.Sleep Method. Are there any better solutions?
If your spec says something like 'Always wait at least two seconds before continuing', use Sleep().
If your spec says something like 'Wait for up to two seconds for a signal from another thread and return an error if timed out' use an event object.
It's basically that simple.
There are essentially no 'performance differences' re. timing accuracy since both calls use the same mechanism for timeouts.
'Better' solutions - what is 'better'? Better in what respect?
1.Thread.Sleep(timeout) causes an unconditional wait before execution is resumed.
2.WaitOne(timeout) causes the thread to wait until either
- the event is triggered,
- The timeout is reached
I would argue against ever using Thread.Sleep(...)
... simply because I dislike blocking a thread unnecessarily... So using a WaitHandle
I think is the superior option.
Alternative
If you're code's elegance will suffer from using WaitHandle
, then have you considered await Task.Delay(...)
? This will give functionality simliar to Thread.Sleep(...)
without blocking the thread.
Task.Delay()
actually uses a timer. –
Darfur © 2022 - 2024 — McMap. All rights reserved.
AutoResetEvent
, callWaitOne
, dispose the event, when you can simply doThread.Sleep
? – Warlock