Don't understand the need for Monitor.Pulse()

前端 未结 3 620
广开言路
广开言路 2021-02-05 05:32

According to MSDN, Monitor.Wait():

Releases the lock on an object and blocks the current thread until it reacquires the lock.

3条回答
  •  孤独总比滥情好
    2021-02-05 05:58

    Read the Remarks section of the linked MSDN page:

    When a thread calls Wait, it releases the lock on the object and enters the object's waiting queue. The next thread in the object's ready queue (if there is one) acquires the lock and has exclusive use of the object. All threads that call Wait remain in the waiting queue until they receive a signal from Pulse or PulseAll, sent by the owner of the lock. If Pulse is sent, only the thread at the head of the waiting queue is affected. If PulseAll is sent, all threads that are waiting for the object are affected. When the signal is received, one or more threads leave the waiting queue and enter the ready queue. A thread in the ready queue is permitted to reacquire the lock.

    This method returns when the calling thread reacquires the lock on the object. Note that this method blocks indefinitely if the holder of the lock does not call Pulse or PulseAll.

    So, basically, when you call Monitor.Wait, your thread is in the waiting queue. For it to re-acquire the lock, it needs to be in the ready queue. Monitor.Pulse moves the first thread in the waiting queue to the ready queue and thus allows for it to re-acquire the lock.

提交回复
热议问题