Monitor.TryEnter Method

Definition

Attempts to acquire an exclusive lock on the specified object.

Overloads

TryEnter(Object, TimeSpan, Boolean)

Attempts, for the specified amount of time, to acquire an exclusive lock on the specified object, and atomically sets a value that indicates whether the lock was taken.

TryEnter(Object, Int32, Boolean)

Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object, and atomically sets a value that indicates whether the lock was taken.

TryEnter(Object, TimeSpan)

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

TryEnter(Object, Boolean)

Attempts to acquire an exclusive lock on the specified object, and atomically sets a value that indicates whether the lock was taken.

TryEnter(Object)

Attempts to acquire an exclusive lock on the specified object.

TryEnter(Object, Int32)

Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object.

TryEnter(Object, TimeSpan, Boolean)

Source:
Monitor.cs
Source:
Monitor.cs
Source:
Monitor.cs

Attempts, for the specified amount of time, to acquire an exclusive lock on the specified object, and atomically sets a value that indicates whether the lock was taken.

C#
public static void TryEnter(object obj, TimeSpan timeout, ref bool lockTaken);

Parameters

obj
Object

The object on which to acquire the lock.

timeout
TimeSpan

The amount of time to wait for the lock. A value of -1 millisecond specifies an infinite wait.

lockTaken
Boolean

The result of the attempt to acquire the lock, passed by reference. The input must be false. The output is true if the lock is acquired; otherwise, the output is false. The output is set even if an exception occurs during the attempt to acquire the lock.

Exceptions

The input to lockTaken is true.

The obj parameter is null.

The value of timeout in milliseconds is negative and is not equal to Infinite (-1 millisecond), or is greater than Int32.MaxValue.

Remarks

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

If the lock was not taken because an exception was thrown, the variable specified for the lockTaken parameter is false after this method ends. This allows the program to determine, in all cases, whether it is necessary to release the lock.

Note

Use Monitor to lock objects (that is, reference types), not value types. For more information, see the Monitor class topic.

To ensure that the thread does not enter the critical section, you should examine the value of lockTaken and execute code in the critical section only if its 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.

C#
var lockObj = new Object();
var timeout = TimeSpan.FromMilliseconds(500);
bool lockTaken = false;

try {
   Monitor.TryEnter(lockObj, timeout, ref lockTaken);
   if (lockTaken) {
      // The critical section.
   }
   else {
      // The lock was not acquired.
   }
}
finally {
   // Ensure that the lock is released.
   if (lockTaken) {
      Monitor.Exit(lockObj);
   }
}

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

TryEnter(Object, Int32, Boolean)

Source:
Monitor.CoreCLR.cs
Source:
Monitor.CoreCLR.cs
Source:
Monitor.CoreCLR.cs

Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object, and atomically sets a value that indicates whether the lock was taken.

C#
public static void TryEnter(object obj, int millisecondsTimeout, ref bool lockTaken);

Parameters

obj
Object

The object on which to acquire the lock.

millisecondsTimeout
Int32

The number of milliseconds to wait for the lock.

lockTaken
Boolean

The result of the attempt to acquire the lock, passed by reference. The input must be false. The output is true if the lock is acquired; otherwise, the output is false. The output is set even if an exception occurs during the attempt to acquire the lock.

Exceptions

The input to lockTaken is true.

The obj parameter is null.

millisecondsTimeout is negative, and not equal to Infinite.

Examples

The following code shows the basic pattern for using the TryEnter(Object, Boolean) method overload. This overload always sets the value of the variable that is passed to the ref parameter (ByRef in Visual Basic) lockTaken, even if the method throws an exception, so the value of the variable is a reliable way to test whether the lock has to be released.

C#
bool acquiredLock = false;

try
{
    Monitor.TryEnter(lockObject, 500, ref acquiredLock);
    if (acquiredLock)
    {

        // Code that accesses resources that are protected by the lock.
    }
    else
    {
    
        // Code to deal with the fact that the lock was not acquired.
    }
}
finally
{
    if (acquiredLock)
    {
        Monitor.Exit(lockObject);
    }
}

Remarks

If the millisecondsTimeout parameter equals Infinite, this method is equivalent to Enter(Object). If millisecondsTimeout equals 0, this method is equivalent to TryEnter(Object).

If the lock was not taken because an exception was thrown, the variable specified for the lockTaken parameter is false after this method ends. This allows the program to determine, in all cases, whether it is necessary to release the lock.

Note

Use Monitor to lock objects (that is, reference types), not value types. For more information, see the Monitor class topic.

To ensure that the thread does not enter the critical section, you should examine the value of lockTaken and execute code in the critical section only if its 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.

C#
var lockObj = new Object();
int timeout = 500;
bool lockTaken = false;

try {
   Monitor.TryEnter(lockObj, timeout, ref lockTaken);
   if (lockTaken) {
      // The critical section.
   }
   else {
      // The lock was not acquired.
   }
}
finally {
   // Ensure that the lock is released.
   if (lockTaken) {
      Monitor.Exit(lockObj);
   }   
}

Applies to

.NET 10 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

TryEnter(Object, TimeSpan)

Source:
Monitor.cs
Source:
Monitor.cs
Source:
Monitor.cs

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

C#
public static bool TryEnter(object obj, TimeSpan timeout);

Parameters

obj
Object

The object on which to acquire the lock.

timeout
TimeSpan

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

The obj parameter is null.

The value of timeout in milliseconds is negative and is not equal to Infinite (-1 millisecond), or is greater than Int32.MaxValue.

Remarks

If the value of the timeout parameter converted to milliseconds equals -1, this method is equivalent to Enter. If the value of timeout equals 0, this method is equivalent to TryEnter.

Note

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

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.

C#
var lockObj = new Object();
var timeout = TimeSpan.FromMilliseconds(500);

if (Monitor.TryEnter(lockObj, timeout)) {
   try {
      // The critical section.
   }
   finally {
      // Ensure that the lock is released.
      Monitor.Exit(lockObj);
   }
}
else {
   // The lock was not acquired.
}

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

TryEnter(Object, Boolean)

Source:
Monitor.CoreCLR.cs
Source:
Monitor.CoreCLR.cs
Source:
Monitor.CoreCLR.cs

Attempts to acquire an exclusive lock on the specified object, and atomically sets a value that indicates whether the lock was taken.

C#
public static void TryEnter(object obj, ref bool lockTaken);

Parameters

obj
Object

The object on which to acquire the lock.

lockTaken
Boolean

The result of the attempt to acquire the lock, passed by reference. The input must be false. The output is true if the lock is acquired; otherwise, the output is false. The output is set even if an exception occurs during the attempt to acquire the lock.

Exceptions

The input to lockTaken is true.

The obj parameter is null.

Examples

The following code shows the basic pattern for using the TryEnter(Object, Boolean) method overload. This overload always sets the value of the variable that is passed to the ref parameter (ByRef in Visual Basic) lockTaken, even if the method throws an exception, so the value of the variable is a reliable way to test whether the lock has to be released.

C#
bool acquiredLock = false;

try
{
    Monitor.TryEnter(lockObject, ref acquiredLock);
    if (acquiredLock)
    {

        // Code that accesses resources that are protected by the lock.
    }
    else
    {
    
        // Code to deal with the fact that the lock was not acquired.
    }
}
finally
{
    if (acquiredLock)
    {
        Monitor.Exit(lockObject);
    }
}

Remarks

If successful, this method acquires an exclusive lock on the obj parameter. This method returns immediately, whether or not the lock is available.

If the lock was not taken because an exception was thrown, the variable specified for the lockTaken parameter is false after this method ends. This allows the program to determine, in all cases, whether it is necessary to release the lock.

This method is similar to Enter(Object, Boolean), but it will never block the current thread. If the thread cannot enter without blocking, the lockTaken argument is set to false when the method returns.

Note

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

To ensure that the thread does not enter the critical section, you should examine the value of lockTaken and execute code in the critical section only if its 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.

C#
var lockObj = new Object();
bool lockTaken = false;

try {
   Monitor.TryEnter(lockObj, ref lockTaken); 
   if (lockTaken) {
      // The critical section.
   }
   else {
      // The lock was not acquired.
   }
}
finally {
   // Ensure that the lock is released.
   if (lockTaken) {
      Monitor.Exit(lockObj);
   }
}

Applies to

.NET 10 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

TryEnter(Object)

Source:
Monitor.CoreCLR.cs
Source:
Monitor.CoreCLR.cs
Source:
Monitor.CoreCLR.cs

Attempts to acquire an exclusive lock on the specified object.

C#
public static bool TryEnter(object obj);

Parameters

obj
Object

The object on which to acquire the lock.

Returns

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

Exceptions

The obj parameter is null.

Examples

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

C#
using System;
using System.Threading;
using System.Collections.Generic;
using System.Text;

class SafeQueue<T>
{
   // 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);
      }
   }

   // 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;
      }
   }

   // Try to add an element to the queue: Add the element to the queue
   // only if the lock becomes available during the specified time
   // interval.
   public bool TryEnqueue(T qValue, int waitTime)
   {
      // Request the lock.
      if (Monitor.TryEnter(m_inputQueue, waitTime))
      {
         try
         {
            m_inputQueue.Enqueue(qValue);
         }
         finally
         {
            // Ensure that the lock is released.
            Monitor.Exit(m_inputQueue);
         }
         return true;
      }
      else
      {
         return false;
      }
   }

   // Lock the queue and dequeue an element.
   public T Dequeue()
   {
      T retval;

      // Request the lock, and block until it is obtained.
      Monitor.Enter(m_inputQueue);
      try
      {
         // When the lock is obtained, dequeue an element.
         retval = m_inputQueue.Dequeue();
      }
      finally
      {
         // Ensure that the lock is released.
         Monitor.Exit(m_inputQueue);
      }

      return retval;
   }

   // Delete all elements that equal the given object.
   public int Remove(T qValue)
   {
      int removedCt = 0;

      // Wait until the lock is available and lock the queue.
      Monitor.Enter(m_inputQueue);
      try
      {
         int counter = m_inputQueue.Count;
         while (counter > 0)
            // Check each element.
         {
            T elem = m_inputQueue.Dequeue();
            if (!elem.Equals(qValue))
            {
               m_inputQueue.Enqueue(elem);
            }
            else
            {
               // Keep a count of items removed.
               removedCt += 1;
            }
            counter = counter - 1;
         }
      }
      finally
      {
         // Ensure that the lock is released.
         Monitor.Exit(m_inputQueue);
      }

      return removedCt;
   }

   // Print all queue elements.
   public string PrintAllElements()
   {
      StringBuilder output = new StringBuilder();

      // Lock the queue.
      Monitor.Enter(m_inputQueue);
      try
      {
         foreach( T elem in m_inputQueue )
         {
            // Print the next element.
            output.AppendLine(elem.ToString());
         }
      }
      finally
      {
         // Ensure that the lock is released.
         Monitor.Exit(m_inputQueue);
      }

      return output.ToString();
   }
}

public class Example
{
   private static SafeQueue<int> q = new SafeQueue<int>();
   private static int threadsRunning = 0;
   private static int[][] results = new int[3][];

   static void Main()
   {
      Console.WriteLine("Working...");

      for(int i = 0; i < 3; i++)
      {
         Thread t = new Thread(ThreadProc);
         t.Start(i);
         Interlocked.Increment(ref threadsRunning);
      }
   }

   private static void ThreadProc(object state)
   {
      DateTime finish = DateTime.Now.AddSeconds(10);
      Random rand = new Random();
      int[] result = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
      int threadNum = (int) state;

      while (DateTime.Now < finish)

      {
         int what = rand.Next(250);
         int how = rand.Next(100);

         if (how < 16)
         {
            q.Enqueue(what);
            result[(int)ThreadResultIndex.EnqueueCt] += 1;
         }
         else if (how < 32)
         {
            if (q.TryEnqueue(what))
            {
               result[(int)ThreadResultIndex.TryEnqueueSucceedCt] += 1;
            }
            else
            {
               result[(int)ThreadResultIndex.TryEnqueueFailCt] += 1;
            }
         }
         else if (how < 48)
         {
            // Even a very small wait significantly increases the success
            // rate of the conditional enqueue operation.
            if (q.TryEnqueue(what, 10))
            {
               result[(int)ThreadResultIndex.TryEnqueueWaitSucceedCt] += 1;
            }
            else
            {
               result[(int)ThreadResultIndex.TryEnqueueWaitFailCt] += 1;
            }
         }
         else if (how < 96)
         {
            result[(int)ThreadResultIndex.DequeueCt] += 1;
            try
            {
               q.Dequeue();
            }
            catch
            {
               result[(int)ThreadResultIndex.DequeueExCt] += 1;
            }
         }
         else
         {
            result[(int)ThreadResultIndex.RemoveCt] += 1;
            result[(int)ThreadResultIndex.RemovedCt] += q.Remove(what);
         }
      }

      results[threadNum] = result;

      if (0 == Interlocked.Decrement(ref threadsRunning))
      {
         StringBuilder sb = new StringBuilder(
            "                               Thread 1 Thread 2 Thread 3    Total\n");

         for(int row = 0; row < 9; row++)
         {
            int total = 0;
            sb.Append(titles[row]);

            for(int col = 0; col < 3; col++)
            {
               sb.Append(String.Format("{0,9}", results[col][row]));
               total += results[col][row];
            }

            sb.AppendLine(String.Format("{0,9}", total));
         }

         Console.WriteLine(sb.ToString());
      }
   }

   private static string[] titles = {
      "Enqueue                       ",
      "TryEnqueue succeeded          ",
      "TryEnqueue failed             ",
      "TryEnqueue(T, wait) succeeded ",
      "TryEnqueue(T, wait) failed    ",
      "Dequeue attempts              ",
      "Dequeue exceptions            ",
      "Remove operations             ",
      "Queue elements removed        "};

   private enum ThreadResultIndex
   {
      EnqueueCt,
      TryEnqueueSucceedCt,
      TryEnqueueFailCt,
      TryEnqueueWaitSucceedCt,
      TryEnqueueWaitFailCt,
      DequeueCt,
      DequeueExCt,
      RemoveCt,
      RemovedCt
   };
}

/* This example produces output similar to the following:

Working...
                               Thread 1 Thread 2 Thread 3    Total
Enqueue                          277382   515209   308464  1101055
TryEnqueue succeeded             276873   514621   308099  1099593
TryEnqueue failed                   109      181      134      424
TryEnqueue(T, wait) succeeded    276913   514434   307607  1098954
TryEnqueue(T, wait) failed            2        0        0        2
Dequeue attempts                 830980  1544081   924164  3299225
Dequeue exceptions                12102    21589    13539    47230
Remove operations                 69550   129479    77351   276380
Queue elements removed            11957    22572    13043    47572
 */

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

Note

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.

C#
var lockObj = new Object();

if (Monitor.TryEnter(lockObj)) {
   try {
      // The critical section.
   }
   finally {
      // Ensure that the lock is released.
      Monitor.Exit(lockObj);
   }
}
else {
   // The lock was not axquired.
}

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

TryEnter(Object, Int32)

Source:
Monitor.CoreCLR.cs
Source:
Monitor.CoreCLR.cs
Source:
Monitor.CoreCLR.cs

Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object.

C#
public static bool TryEnter(object obj, int millisecondsTimeout);

Parameters

obj
Object

The object on which to acquire the lock.

millisecondsTimeout
Int32

The number of milliseconds to wait for the lock.

Returns

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

Exceptions

The obj parameter is null.

millisecondsTimeout is negative, and not equal to Infinite.

Remarks

If the millisecondsTimeout parameter equals Infinite, this method is equivalent to Enter. If millisecondsTimeout equals 0, this method is equivalent to TryEnter.

Note

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.

C#
var lockObj = new Object();
int timeout = 500;

if (Monitor.TryEnter(lockObj, timeout)) {
   try {
      // The critical section.
   }
   finally {
      // Ensure that the lock is released.
      Monitor.Exit(lockObj);
   }
}
else {
   // The lock was not acquired.
}

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0