11

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?

4

3 回答 3

10

1.Thread.Sleep(timeout) 在恢复执行之前导致无条件等待。

2.WaitOne(timeout) 导致线程等待直到

  • 事件被触发,
  • 已达到超时
于 2014-01-22T11:52:31.803 回答
10

如果您的规范说“在继续之前始终等待至少两秒钟”,请使用 Sleep()。

如果您的规范说“等待来自另一个线程的信号最多两秒钟,如果超时则返回错误”,请使用事件对象。

基本上就是这么简单。

基本上没有“性能差异”。计时准确性,因为两个调用都使用相同的超时机制。

“更好”的解决方案——什么是“更好”?在哪些方面更好?

于 2014-01-22T12:45:05.727 回答
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.

于 2014-01-22T12:51:46.413 回答