Waits for notification from an object which called the Pulse or PulseAll method or for a specified timer to elapse.
[Visual Basic] Overloads Public Shared Function Wait( _ ByVal obj As Object, _ ByVal millisecondsTimeout As Integer _ ) As Boolean [C#] public static bool Wait( object obj, int millisecondsTimeout ); [C++] public: static bool Wait( Object* obj, int millisecondsTimeout ); [JScript] public static function Wait( obj : Object, millisecondsTimeout : int ) : Boolean;
True if the wait succeeded or did not time out; otherwise, false.
Exception Type | Condition |
---|---|
ArgumentNullException | If obj is a null reference (in Visual Basic Nothing). |
SynchronizationLockException | Wait is not invoked from within a synchronized block of code. |
ThreadInterruptedException | ThreadInterruptedException if the thread that invokes Wait is later interrupted from the waiting state. This happens when another thread calls this thread's Interrupt method. |
The thread that currently holds the lock on this object invokes this method in order to wait until a condition in the object's state has been met. Shortly after the call to Wait, the thread that invoked Wait releases the lock, enters the waiting queue, and the next thread in the ready queue (if there is one) is allowed to take control of the lock. The thread that invoked Wait remains in the waiting queue until either a thread that holds the lock invokes PulseAll, or it is the next in the queue and a thread that holds the lock invokes Pulse. However, if timeout milliseconds elapse before another thread invokes this object's Pulse or PulseAll method, the original thread is moved to the ready queue in order to regain the lock. Eventually the original thread will enter the ready queue and regain the lock. If the condition in the object's state has not been met, the thread may call Wait again to reenter the waiting queue until it has been met.
If timeout equals 0, the thread that calls Wait releases the lock and then immediately enters the ready queue in order to regain the lock.
Note that a synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state. The Pulse, PulseAll, and Wait methods must be invoked from within a synchronized block of code. The examples below resolve an issue that arises when Pulse is invoked before Wait.
These examples resolve an issue that arises when the Pulse method is invoked before the Wait method. Note: this code is provided for illustrative purposes only; it will not work with current builds.
Example 1 (This code may hang if Pulse is invoked before Wait.)
Monitor Class | Monitor Members | System.Threading Namespace | Monitor.Wait Overload List