Monitor.TryEnter Method (Object)
[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]
Attempts to acquire an exclusive lock on the specified object.
Assembly: mscorlib (in mscorlib.dll)
Parameters
- obj
- Type: System.Object
The object on which to acquire the lock.
| Exception | Condition |
|---|---|
| ArgumentNullException | The obj parameter is Nothing. |
If successful, this method acquires an exclusive lock on the obj parameter. This method returns immediately, whether or not the lock is available.
This method is similar to 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.
The following example demonstrates how to use the TryEnter method. This code is part of a larger example provided for the Enter method.
' Try to add an element to the queue: Add the element to the queue ' only if the lock is immediately available. Public Function TryEnqueue(ByVal qValue As T) As Boolean ' Request the lock. If Monitor.TryEnter(m_inputQueue) Then Try m_inputQueue.Enqueue(qValue) Finally ' Ensure that the lock is released. Monitor.Exit(m_inputQueue) End Try Return True Else Return False End If End Function
Note: