Monitor.TryEnter Method (Object)


Attempts to acquire an exclusive lock on the specified object.

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

static member TryEnter : 
        obj:Object -> bool


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.

Exception Condition

The obj parameter is null.

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 the current thread. If the thread cannot enter without blocking, the method returns false,.


Use Monitor to lock objects (that is, reference types), not value types. For details, see the Monitor article.

To ensure that the thread does not enter the critical section, you should examine the method's return value and execute code in the critical section only if its return value is true. The following code fragment shows the pattern used to call this method. Note that you should call Exit in a finally block to ensure that the calling thread releases its lock on the critical section if an exception occurs.

No code example is currently available or this language may not be supported.

The following code example demonstrates how to use the TryEnter method.

No code example is currently available or this language may not be supported.

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top