Monitor.TryEnter Method (Object)

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Attempts to acquire an exclusive lock on the specified object.

Namespace:  System.Threading
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
Public Shared Function TryEnter ( _
    obj As Object _
) As Boolean
public static bool TryEnter(
    Object obj
)

Parameters

  • obj
    Type: System.Object
    The object on which to acquire the lock.

Return Value

Type: System.Boolean
true if the current thread acquires the lock; otherwise, false.

Exceptions

Exception Condition
ArgumentNullException

The obj parameter is nulla null reference (Nothing in Visual Basic).

Remarks

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.

NoteNote:

Use Monitor to lock objects (that is, reference types), not value types. For details, see Enter and the conceptual topic Monitors.

Examples

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
// Try to add an element to the queue: Add the element to the queue 
// only if the lock is immediately available.
public bool TryEnqueue(T qValue)
{
   // Request the lock.
   if (Monitor.TryEnter(m_inputQueue))
   {
      try
      {
         m_inputQueue.Enqueue(qValue);
      }
      finally
      {
         // Ensure that the lock is released.
         Monitor.Exit(m_inputQueue);
      }
      return true;
   }
   else
   {
      return false;
   }
}

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.