13

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?

Ryszard Dżegan
  • 24,366
  • 6
  • 38
  • 56
  • 'Better' depends on the circumstances. Waiting is basically wrong so no 'best practice' here. – H H Jan 22 '14 at 11:50
  • 2
    What is bad in waiting when all I need is only waiting? I just wonder which method is better from performance perspective or if they behave in the same manner under the hood, then I will make my decision basing on other factors such as readability. – Ryszard Dżegan Jan 22 '14 at 11:57
  • Why would you create an `AutoResetEvent`, call `WaitOne`, dispose the event, when you can simply do `Thread.Sleep`? – Henrik Jan 22 '14 at 12:02
  • @Henrik I can invoke _WaitOne_ many times in the loop without disposing _AutoResetEvent_. What would be the difference then? Ok, one minus is that I need to create an instance of wait handle, but I do that only once, so it is negligible. – Ryszard Dżegan Jan 22 '14 at 12:10

3 Answers3

12

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?

Martin James
  • 24,453
  • 3
  • 36
  • 60
10

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
santosh singh
  • 27,666
  • 26
  • 83
  • 129
1

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.

poy
  • 10,063
  • 9
  • 49
  • 74
  • ?? Waiting on an event handle blocks the thread, just like sleep() calls. – Martin James Jan 22 '14 at 19:25
  • @MartinJames But without blocking the thread... `Task.Delay()` actually uses a timer. – poy Jan 22 '14 at 19:57
  • 1
    Asynchronous execution on another thread, eg. by Task.Delay(), is surely possible, but the OP is asking about synchronous delays in the calling thread. – Martin James Jan 23 '14 at 08:17