public sealed class Monitor
|
Monitor has the following features:
The following information is maintained for each synchronized object:
The following table describes the actions that can be taken by threads that access synchronized objects:
Action | Description |
---|---|
Monitor.Enter , Monitor.TryEnter | Acquires a lock for an object. This action also marks the beginning of a critical section. No other thread can enter the critical section unless it is executing the instructions in the critical section using a different locked object. |
Monitor.Wait | Releases the lock on an object in order to permit other threads to lock and access the object. The calling thread waits while another thread accesses the object. Pulse signals are used to notify waiting threads about changes to an object's state. |
Monitor.Pulse (signal), Monitor.PulseAll | Sends a signal to one or more waiting threads. The signal notifies a waiting thread that the state of the locked object has changed, and the owner of the lock is ready to release the lock. The waiting thread is placed in the object's ready queue so that it may eventually receive the lock for the object. Once the thread has the lock, it can check the new state of the object to see if the required state has been reached. |
Monitor.Exit | Releases the lock on an object. This action also marks the end of a critical section protected by the locked object. |
Use the Enter and Exit methods to mark the beginning and end of a critical section. If the critical section is a set of contiguous instructions, then the lock acquired by the Enter method guarantees that only a single thread can execute the enclosed code with the locked object. In this case, it is recommended you place those instructions in a try block and place the Exit instruction in a finally block. This facility is typically used to synchronize access to a static or instance method of a class. If an instance method requires synchronized thread access, it invokes the Enter and corresponding Exit methods using the current instance as the object to lock. Since only one thread can hold the lock on the current instance, the method can only be executed by one thread at a time. Static methods are protected in a similar fashion using the Type of the current instance as the locked object. The functionality provided by the Enter and Exit methods is identical to that provided by the C# lock statement.
If a critical section spans an entire method, the locking facility described above can be achieved by placing the MethodImplAttribute on the method, and specifying the MethodImplOptions.Synchronized value in the constructor of MethoImplAttribute. Using this attribute, the Enter and Exit statements are not needed. Note that the attribute causes the current thread to hold the lock until the method returns; if the lock can be released sooner, use the Monitor class or the C# lock statement instead of the attribute.
While it is possible for the Enter and Exit statements that lock and release a given object to cross member or class boundaries or both, this practice is not recommended.
When selecting an object on which to synchronize, you should lock only on private or internal objects. Locking on external objects might result in deadlocks, because unrelated code could choose the same objects to lock on for different purposes.
Enter | Acquires an exclusive lock on the specified object. |
Equals (inherited from System.Object) |
See base class member description: System.Object.Equals Derived from System.Object, the primary base class for all objects. |
Exit | Releases an exclusive lock on the specified object. |
GetHashCode (inherited from System.Object) |
See base class member description: System.Object.GetHashCode Derived from System.Object, the primary base class for all objects. |
GetType (inherited from System.Object) |
See base class member description: System.Object.GetType Derived from System.Object, the primary base class for all objects. |
Pulse | Notifies a thread in the waiting queue of a change in the locked object's state. |
PulseAll | Notifies all waiting threads of a change in the object's state. |
ToString (inherited from System.Object) |
See base class member description: System.Object.ToString Derived from System.Object, the primary base class for all objects. |
TryEnter | Overloaded:TryEnter(object obj) Attempts to acquire an exclusive lock on the specified object. |
TryEnter | Overloaded:TryEnter(object obj, int millisecondsTimeout) Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object. |
TryEnter | Overloaded:TryEnter(object obj, TimeSpan timeout) Attempts, for the specified amount of time, to acquire an exclusive lock on the specified object. |
Wait | Overloaded:Wait(object obj) Releases the lock on an object and blocks the current thread until it reacquires the lock. |
Wait | Overloaded:Wait(object obj, int millisecondsTimeout) Releases the lock on an object and blocks the current thread until it reacquires the lock or a specified amount of time elapses. |
Wait | Overloaded:Wait(object obj, TimeSpan timeout) Releases the lock on an object and blocks the current thread until it reacquires the lock or a specified amount of time elapses. |
Wait | Overloaded:Wait(object obj, int millisecondsTimeout, bool exitContext) Waits for notification from an object that called the Monitor.Pulse or Monitor.PulseAll method or for a specified timer to elapse. This method also specifies whether the synchronization domain for the context (if in a synchronized context) is exited before the wait and reacquired. |
Wait | Overloaded:Wait(object obj, TimeSpan timeout, bool exitContext) Releases the lock on an object and blocks the current thread until it reacquires the lock, or until a specified amount of time elapses, optionally exiting the synchronization domain for the synchronized context before the wait and reacquiring the domain. |
Finalize (inherited from System.Object) |
See base class member description: System.Object.Finalize Derived from System.Object, the primary base class for all objects. |
MemberwiseClone (inherited from System.Object) |
See base class member description: System.Object.MemberwiseClone Derived from System.Object, the primary base class for all objects. |
Hierarchy:
public static void Enter( |
obj
Exception Type | Condition |
---|---|
ArgumentNullException | The obj parameter is null. |
Thread.Interrupt can interrupt threads waiting to enter a Monitor on an object. A ThreadInterruptedException will be thrown.
Invoking this member is identical to using the C# lock statement.
//Define the queue to safe thread access. private Queue m_inputQueue; public MonitorSample() { m_inputQueue = new Queue(); } //Add an element to the queue and obtain the monitor lock for the queue object. public void AddElement(object qValue) { //Lock the queue. Monitor.Enter(m_inputQueue); //Add element m_inputQueue.Enqueue(qValue); //Unlock the queue. Monitor.Exit(m_inputQueue); } //Try to add an element to the queue. //Add the element to the queue only if the queue object is unlocked. public bool AddElementWithoutWait(object qValue) { //Check if the queue is locked if(!Monitor.TryEnter(m_inputQueue)) return false; m_inputQueue.Enqueue(qValue); Monitor.Exit(m_inputQueue); return true; } //Try to add an element to the queue. //Add the element to the queue only if during the specified time the queue object will be unlocked. public bool WaitToAddElement(object qValue, int waitTime) { //Wait while the queue is locked. if(!Monitor.TryEnter(m_inputQueue,waitTime)) return false; m_inputQueue.Enqueue(qValue); Monitor.Exit(m_inputQueue); return true; } //Delete all elements that equal the given object and obtain the monitor lock for the queue object. public void DeleteElement(object qValue) { //Lock the queue. Monitor.Enter(m_inputQueue); int counter = m_inputQueue.Count; while(counter > 0) { //Check each element. object elm = m_inputQueue.Dequeue(); if(!elm.Equals(qValue)) { m_inputQueue.Enqueue(elm); } --counter; } //Unlock the queue. Monitor.Exit(m_inputQueue); } //Print all queue elements. public void PrintAllElements() { //Lock the queue. Monitor.Enter(m_inputQueue); IEnumerator elmEnum = m_inputQueue.GetEnumerator(); while(elmEnum.MoveNext()) { //Print the next element. Console.WriteLine(elmEnum.Current.ToString()); } //Unlock the queue. Monitor.Exit(m_inputQueue); }
public static void Exit( |
obj
Exception Type | Condition |
---|---|
ArgumentNullException | The obj parameter is null. |
SynchronizationLockException | The current thread does not own the lock for the specified object. |
If the lock is released and other threads are in the ready queue for the object, one of the threads acquires the lock. If other threads are in the waiting queue waiting to acquire the lock, they are not automatically moved to the ready queue when the owner of the lock calls Exit. To move one or more waiting threads into the ready queue, call Monitor.Pulse or Monitor.PulseAll before invoking Exit.
//Define the queue to safe thread access. private Queue m_inputQueue; public MonitorSample() { m_inputQueue = new Queue(); } //Add an element to the queue and obtain the monitor lock for the queue object. public void AddElement(object qValue) { //Lock the queue. Monitor.Enter(m_inputQueue); //Add element m_inputQueue.Enqueue(qValue); //Unlock the queue. Monitor.Exit(m_inputQueue); } //Try to add an element to the queue. //Add the element to the queue only if the queue object is unlocked. public bool AddElementWithoutWait(object qValue) { //Check if the queue is locked if(!Monitor.TryEnter(m_inputQueue)) return false; m_inputQueue.Enqueue(qValue); Monitor.Exit(m_inputQueue); return true; } //Try to add an element to the queue. //Add the element to the queue only if during the specified time the queue object will be unlocked. public bool WaitToAddElement(object qValue, int waitTime) { //Wait while the queue is locked. if(!Monitor.TryEnter(m_inputQueue,waitTime)) return false; m_inputQueue.Enqueue(qValue); Monitor.Exit(m_inputQueue); return true; } //Delete all elements that equal the given object and obtain the monitor lock for the queue object. public void DeleteElement(object qValue) { //Lock the queue. Monitor.Enter(m_inputQueue); int counter = m_inputQueue.Count; while(counter > 0) { //Check each element. object elm = m_inputQueue.Dequeue(); if(!elm.Equals(qValue)) { m_inputQueue.Enqueue(elm); } --counter; } //Unlock the queue. Monitor.Exit(m_inputQueue); } //Print all queue elements. public void PrintAllElements() { //Lock the queue. Monitor.Enter(m_inputQueue); IEnumerator elmEnum = m_inputQueue.GetEnumerator(); while(elmEnum.MoveNext()) { //Print the next element. Console.WriteLine(elmEnum.Current.ToString()); } //Unlock the queue. Monitor.Exit(m_inputQueue); }
~Monitor(); |
public virtual int GetHashCode(); |
public Type GetType(); |
protected object MemberwiseClone(); |
public static void Pulse( |
obj
Exception Type | Condition |
---|---|
ArgumentNullException | The obj parameter is null. |
SynchronizationLockException | The calling thread does not own the lock for the specified object. |
The thread that currently owns the lock on the specified object invokes this method to signal the next thread in line for the lock. Upon receiving the pulse, the waiting thread is moved to the ready queue. When the thread that invoked Pulse releases the lock, the next thread in the ready queue (which is not necessarily the thread that was pulsed) acquires 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, Monitor.PulseAll, and Monitor.Wait methods must be invoked from within a synchronized block of code. The remarks for Wait address an issue that arises when Pulse is invoked before Wait.
To signal multiple threads, use the Monitor.PulseAll method.
using System; using System.Threading; using System.Collections; namespace MonitorCS1 { class MonitorSample { const int MAX_LOOP_TIME = 1000; Queue m_smplQueue; public MonitorSample() { m_smplQueue = new Queue(); } public void FirstThread() { int counter = 0; lock(m_smplQueue) { while(counter < MAX_LOOP_TIME) { //Wait, if the queue is busy. Monitor.Wait(m_smplQueue); //Push one element. m_smplQueue.Enqueue(counter); //Release the waiting thread. Monitor.Pulse(m_smplQueue); counter++; } } } public void SecondThread() { lock(m_smplQueue) { //Release the waiting thread. Monitor.Pulse(m_smplQueue); //Wait in the loop, while the queue is busy. //Exit on the timeout when the first thread stopped. while(Monitor.Wait(m_smplQueue,1000)) { //Pop the first element. int counter = (int)m_smplQueue.Dequeue(); //Print the first element. Console.WriteLine(counter.ToString()); //Release waiting thread. Monitor.Pulse(m_smplQueue); } } } //Return the number of the queue elements. public int GetQueueCount() { return m_smplQueue.Count; } static void Main(string[] args) { //Create the MonitorSample object. MonitorSample test = new MonitorSample(); //Create the first thread. Thread tFirst = new Thread(new ThreadStart(test.FirstThread)); //Create the second thread. Thread tSecond = new Thread(new ThreadStart(test.SecondThread)); //Start threads. tFirst.Start(); tSecond.Start(); //wait to the end of the two threads tFirst.Join(); tSecond.Join(); //Print the number of the queue elements. Console.WriteLine("Queue Count = " + test.GetQueueCount().ToString()); } } }
public static void PulseAll( |
obj
Exception Type | Condition |
---|---|
ArgumentNullException | The obj parameter is null. |
SynchronizationLockException | The calling thread does not own the lock for the specified object. |
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 Monitor.Pulse, PulseAll, and Monitor.Wait methods must be invoked from within a synchronized block of code. The remarks for Wait address an issue that arises when Monitor.Pulse is invoked before Monitor.Wait.
To signal a single thread, use the Pulse method.
public virtual string ToString(); |
obj
Exception Type | Condition |
---|---|
ArgumentNullException | The obj parameter is null. |
ArgumentException | The obj parameter is a value type. |
This method is similar to Monitor.Enter, but it will never block. If the thread cannot enter without blocking, the method returns false, and the thread does not enter the critical section.
//Define the queue to safe thread access. private Queue m_inputQueue; public MonitorSample() { m_inputQueue = new Queue(); } //Add an element to the queue and obtain the monitor lock for the queue object. public void AddElement(object qValue) { //Lock the queue. Monitor.Enter(m_inputQueue); //Add element m_inputQueue.Enqueue(qValue); //Unlock the queue. Monitor.Exit(m_inputQueue); } //Try to add an element to the queue. //Add the element to the queue only if the queue object is unlocked. public bool AddElementWithoutWait(object qValue) { //Check if the queue is locked if(!Monitor.TryEnter(m_inputQueue)) return false; m_inputQueue.Enqueue(qValue); Monitor.Exit(m_inputQueue); return true; } //Try to add an element to the queue. //Add the element to the queue only if during the specified time the queue object will be unlocked. public bool WaitToAddElement(object qValue, int waitTime) { //Wait while the queue is locked. if(!Monitor.TryEnter(m_inputQueue,waitTime)) return false; m_inputQueue.Enqueue(qValue); Monitor.Exit(m_inputQueue); return true; } //Delete all elements that equal the given object and obtain the monitor lock for the queue object. public void DeleteElement(object qValue) { //Lock the queue. Monitor.Enter(m_inputQueue); int counter = m_inputQueue.Count; while(counter > 0) { //Check each element. object elm = m_inputQueue.Dequeue(); if(!elm.Equals(qValue)) { m_inputQueue.Enqueue(elm); } --counter; } //Unlock the queue. Monitor.Exit(m_inputQueue); } //Print all queue elements. public void PrintAllElements() { //Lock the queue. Monitor.Enter(m_inputQueue); IEnumerator elmEnum = m_inputQueue.GetEnumerator(); while(elmEnum.MoveNext()) { //Print the next element. Console.WriteLine(elmEnum.Current.ToString()); } //Unlock the queue. Monitor.Exit(m_inputQueue); }
obj
millisecondsTimeout
Exception Type | Condition |
---|---|
ArgumentNullException | The obj parameter is null. |
ArgumentException | The obj parameter is a value type. |
ArgumentOutOfRangeException | millisecondsTimeout is negative, and not equal to Timeout.Infinite. |
obj
timeout
Exception Type | Condition |
---|---|
ArgumentNullException | The obj parameter is null. |
ArgumentException | The obj parameter is a value type. |
ArgumentOutOfRangeException | The value of timeout in milliseconds is negative and is not equal to Timeout.Infinite, or is greater than Int32.MaxValue. |
obj
Exception Type | Condition |
---|---|
ArgumentNullException | The obj parameter is null. |
SynchronizationLockException | The calling thread does not own the lock for the specified object. |
ThreadInterruptedException | The thread that invokes Wait is later interrupted from the waiting state. This happens when another thread calls this thread's Thread.Interrupt method. |
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 Monitor.Pulse or Monitor.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.
The caller executes Wait once, regardless of the number of times Monitor.Enter has been invoked for the specified object. Conceptually, the Wait method stores the number of times the caller invoked Enter on the object and invokes Exit as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls Enter as many times as necessary to restore the saved Enter count for the caller. Calling Wait releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released.
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 Monitor.Pulse, Monitor.PulseAll, and Wait methods must be invoked from within a synchronized block of code.obj
millisecondsTimeout
Exception Type | Condition |
---|---|
ArgumentNullException | The obj parameter is null. |
SynchronizationLockException | The calling thread does not own the lock for the specified object. |
ThreadInterruptedException | The thread that invokes Wait is later interrupted from the waiting state. This happens when another thread calls this thread's Thread.Interrupt method. |
ArgumentOutOfRangeException | The value of the millisecondsTimeout parameter is negative, and is not equal to Timeout.Infinite. |
This method behaves identically to Wait, except that it does not block indefinitely unless Timeout.Infinite is specified for the millisecondsTimeout parameter. Once the specified time has elapsed, this method returns a value that indicates whether or not the lock has been reacquired by the caller. If millisecondsTimeout equals 0, this method returns immediately.
The thread that currently owns the lock on the specified object invokes this method in order to release the object so that another thread can access it. The caller is blocked while waiting to reacquire the lock. This method is called when the caller is waiting for a change in the state of the object that will occur as a result of another thread's operations on the object.
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. The thread that invoked Wait remains in the waiting queue until either a thread that holds the lock invokes Monitor.PulseAll, or it is the next in the queue and a thread that holds the lock invokes Monitor.Pulse. However, if millisecondsTimeout elapses before another thread invokes this object's Monitor.Pulse or Monitor.PulseAll method, the original thread is moved to the ready queue in order to regain the lock. If the condition in the object's state has not been met, the thread might call Wait again to reenter the waiting queue until it has been met.
Note that if Timeout.Infinite is specified for the millisecondsTimeout parameter, this method blocks indefinitely if the holder of the lock does not call Monitor.Pulse or Monitor.PulseAll.
The caller executes Wait once, regardless of the number of times Monitor.Enter has been invoked for the specified object. Conceptually, the Wait method stores the number of times the caller invoked Monitor.Enter on the object and invokes Monitor.Exit as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls Monitor.Enter as many times as necessary to restore the saved Monitor.Enter count for the caller.Calling Wait releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released.
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 Monitor.Pulse, Monitor.PulseAll, and Wait methods must be invoked from within a synchronized block of code.
obj
timeout
Exception Type | Condition |
---|---|
ArgumentNullException | The obj parameter is null. |
SynchronizationLockException | The calling thread does not own the lock for the specified object. |
ThreadInterruptedException | The thread that invokes Wait is later interrupted from the waiting state. This happens when another thread calls this thread's Thread.Interrupt method. |
ArgumentOutOfRangeException | The value of the timeout parameter in milliseconds is negative and is not equal to Timeout.Infinite, or is greater than Int32.MaxValue. |
This method behaves identically to Wait, except that it does not block indefinitely unless Timeout.Infinite milliseconds is specified for the timeout parameter. Once the specified time has elapsed, this method returns a value that indicates whether or not the lock has been reacquired by the caller. 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.
The thread that currently owns the lock on the specified object invokes this method in order to release the object so that another thread can access it. The caller is blocked while waiting to reacquire the lock. This method is called when the caller is waiting for a change in the state of the object that will occur as a result of another thread's operations on the object.
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. The thread that invoked Wait remains in the waiting queue until either a thread that holds the lock invokes Monitor.PulseAll, or it is the next in the queue and a thread that holds the lock invokes Monitor.Pulse. However, if timeout elapses before another thread invokes this object's Monitor.Pulse or Monitor.PulseAll method, the original thread is moved to the ready queue in order to regain the lock. If the condition in the object's state has not been met, the thread might call Wait again to reenter the waiting queue until it has been met.
Note that if Timeout.Infinite is specified for the timeout parameter, this method blocks indefinitely if the holder of the lock does not call Monitor.Pulse or Monitor.PulseAll.
The caller executes Wait once, regardless of the number of times Monitor.Enter has been invoked for the specified object. Conceptually, the Wait method stores the number of times the caller invoked Monitor.Enter on the object and invokes Monitor.Exit as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls Monitor.Enter as many times as necessary to restore the saved Monitor.Enter count for the caller. Calling Wait releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released.
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 Monitor.Pulse, Monitor.PulseAll, and Wait methods must be invoked from within a synchronized block of code.
obj
millisecondsTimeout
exitContext
Exception Type | Condition |
---|---|
ArgumentNullException | The obj parameter is null. |
SynchronizationLockException | Wait is not invoked from within a synchronized block of code. |
ThreadInterruptedException | The thread that invokes Wait is later interrupted from the waiting state. This happens when another thread calls this thread's Thread.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 and enters the waiting queue. At this point, 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 Monitor.PulseAll, or it is the next in the queue and a thread that holds the lock invokes Monitor.Pulse. However, if millisecondsTimeout elapses before another thread invokes this object's Monitor.Pulse or Monitor.PulseAll method, the original thread is moved to the ready queue in order to regain the lock. If the condition in the object's state has not been met, the thread might 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 Monitor.Pulse, Monitor.PulseAll, and Wait methods must be invoked from within a synchronized block of code.
using System; using System.Threading; using System.Collections; namespace MonitorCS1 { class MonitorSample { const int MAX_LOOP_TIME = 1000; Queue m_smplQueue; public MonitorSample() { m_smplQueue = new Queue(); } public void FirstThread() { int counter = 0; lock(m_smplQueue) { while(counter < MAX_LOOP_TIME) { //Wait, if the queue is busy. Monitor.Wait(m_smplQueue); //Push one element. m_smplQueue.Enqueue(counter); //Release the waiting thread. Monitor.Pulse(m_smplQueue); counter++; } } } public void SecondThread() { lock(m_smplQueue) { //Release the waiting thread. Monitor.Pulse(m_smplQueue); //Wait in the loop, while the queue is busy. //Exit on the timeout when the first thread stopped. while(Monitor.Wait(m_smplQueue,1000)) { //Pop the first element. int counter = (int)m_smplQueue.Dequeue(); //Print the first element. Console.WriteLine(counter.ToString()); //Release waiting thread. Monitor.Pulse(m_smplQueue); } } } //Return the number of the queue elements. public int GetQueueCount() { return m_smplQueue.Count; } static void Main(string[] args) { //Create the MonitorSample object. MonitorSample test = new MonitorSample(); //Create the first thread. Thread tFirst = new Thread(new ThreadStart(test.FirstThread)); //Create the second thread. Thread tSecond = new Thread(new ThreadStart(test.SecondThread)); //Start threads. tFirst.Start(); tSecond.Start(); //wait to the end of the two threads tFirst.Join(); tSecond.Join(); //Print the number of the queue elements. Console.WriteLine("Queue Count = " + test.GetQueueCount().ToString()); } } }
obj
timeout
exitContext
Exception Type | Condition |
---|---|
ArgumentNullException | The obj parameter is null. |
ArgumentException | The timeout parameter is negative or greater than Int32.MaxValue. |
SynchronizationLockException | Wait is not invoked from within a synchronized block of code. |
ThreadInterruptedException | The thread that invokes Wait is later interrupted from the waiting state. This happens when another thread calls this thread's Thread.Interrupt method. |
ArgumentOutOfRangeException | The timeout parameter is negative or greater than Int32.MaxValue. |
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 Monitor.Pulse, Monitor.PulseAll, and Wait methods must be invoked from within a synchronized block of code.