System.Threading.Monitor.TryEnter Method

Attempts, for the specified amount of time, to acquire an exclusive lock on the specified object.

Syntax

public static bool TryEnter (object obj, TimeSpan timeout)

Parameters

timeout
A TimeSpan representing the amount of time to wait for the lock. A value of –1 millisecond specifies an infinite wait.
obj
The object on which to acquire the lock.
timeout
A TimeSpan representing the amount of time to wait for the lock. A value of –1 millisecond specifies an infinite wait.

Returns

true if the current thread acquires the lock; otherwise, false.

Exceptions

TypeReason
ArgumentNullException obj is null.
ArgumentOutOfRangeExceptionThe value of timeout in milliseconds is negative and is not equal to Timeout.Infinite , or is greater than int.MaxValue .

Remarks

If the value of the timeout parameter converted to milliseconds equals –1, this method is equivalent to Monitor.Enter(object). If the value of timeout equals 0, this method is equivalent to Monitor.TryEnter(object).

Note:

Use System.Threading.Monitor to lock objects (that is, reference types), not value types. For details, see Monitor.Enter(object) and the conceptual topic [<topic://cpconMonitor>].

Requirements

Namespace: System.Threading
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0