(以下项目有不同的目标,但我很想知道它们是如何“暂停”的)
问题
Thread.sleep
- 它会影响系统的性能吗?它会占用线程等待吗?
Monitor.Wait
呢?他们“等待”的方式有什么不同?他们会在等待时占用线程吗?
RegisteredWaitHandle
怎么样?此方法接受等待时执行的委托(delegate)
句柄发出信号。在等待期间,它不会占用线程。
所以一些线程被暂停并且可以被委托(delegate)唤醒,而其他线程只是等待?旋转 ?
有人可以把事情说清楚吗?
编辑
http://www.albahari.com/threading/part2.aspx
最佳答案
Thread.Sleep
和Monitor.Wait
都将线程放在the WaitSleepJoin
state 中:
WaitSleepJoin: The thread is blocked. This could be the result of calling Thread::Sleep or Thread::Join, of requesting a lock — for example, by calling Monitor::Enter or Monitor::Wait — or of waiting on a thread synchronization object such as ManualResetEvent.
RegisteredWaitHandle
是通过调用RegisterWaitForSingleObject获得的并传递一个 WaitHandle
。通常此类的所有后代都使用阻塞机制,因此调用 Wait
会再次将线程放入 WaitSleepJoin
(例如 AutoResetEvent
)。
这是来自 MSDN 的另一段引述:
The RegisterWaitForSingleObject method checks the current state of the specified object's WaitHandle. If the object's state is unsignaled, the method registers a wait operation. The wait operation is performed by a thread from the thread pool. The delegate is executed by a worker thread when the object's state becomes signaled or the time-out interval elapses.
因此池中的线程确实在等待信号。
关于c# - Thread.sleep vs Monitor.Wait vs RegisteredWaitHandle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11381771/