Monitor.Exit Method
Microsoft Silverlight will reach end of support after October 2021. Learn more.
Releases an exclusive lock on the specified object.
Namespace: System.Threading
Assembly: mscorlib (in mscorlib.dll)
Syntax
'Declaration
<SecuritySafeCriticalAttribute> _
Public Shared Sub Exit ( _
obj As Object _
)
[SecuritySafeCriticalAttribute]
public static void Exit(
Object obj
)
Parameters
- obj
Type: System.Object
The object on which to release the lock.
Exceptions
Exception | Condition |
---|---|
ArgumentNullException | The obj parameter is nulla null reference (Nothing in Visual Basic). |
SynchronizationLockException | The current thread does not own the lock for the specified object. |
Remarks
The calling thread must own the lock on the obj parameter. If the calling thread owns the lock on the specified object, and has made an equal number of Exit and Enter calls for the object, then the lock is released. If the calling thread has not invoked Exit as many times as Enter, the lock is not released.
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 Pulse or PulseAll before invoking Exit.
Examples
The following example demonstrates how to use the Exit method. This code is part of a larger example provided for the Enter method.
' A queue that is protected by Monitor.
Private m_inputQueue As New Queue(Of T)
' Lock the queue and add an element.
Public Sub Enqueue(ByVal qValue As T)
' Request the lock, and block until it is obtained.
Monitor.Enter(m_inputQueue)
Try
' When the lock is obtained, add an element.
m_inputQueue.Enqueue(qValue)
Finally
' Ensure that the lock is released.
Monitor.Exit(m_inputQueue)
End Try
End Sub
// A queue that is protected by Monitor.
private Queue<T> m_inputQueue = new Queue<T>();
// Lock the queue and add an element.
public void Enqueue(T qValue)
{
// Request the lock, and block until it is obtained.
Monitor.Enter(m_inputQueue);
try
{
// When the lock is obtained, add an element.
m_inputQueue.Enqueue(qValue);
}
finally
{
// Ensure that the lock is released.
Monitor.Exit(m_inputQueue);
}
}
Version Information
Silverlight
Supported in: 5, 4, 3
Silverlight for Windows Phone
Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0
XNA Framework
Supported in: Xbox 360, Windows Phone OS 7.0
Platforms
For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.
See Also