Monitor.TryEnter 方法

定义

尝试获取指定对象的排他锁。

重载

TryEnter(Object, TimeSpan, Boolean)

在指定的一段时间内尝试获取指定对象上的排他锁,并自动设置一个值,指示是否获得了该锁。

TryEnter(Object, Int32, Boolean)

在指定的毫秒数内尝试获取指定对象上的排他锁,并自动设置一个值,指示是否获取了该锁。

TryEnter(Object, TimeSpan)

在指定的时间内尝试获取指定对象上的排他锁。

TryEnter(Object, Boolean)

尝试获取指定对象上的排他锁,并自动设置一个值,指示是否获取了该锁。

TryEnter(Object)

尝试获取指定对象的排他锁。

TryEnter(Object, Int32)

在指定的毫秒数内尝试获取指定对象上的排他锁。

TryEnter(Object, TimeSpan, Boolean)

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

在指定的一段时间内尝试获取指定对象上的排他锁,并自动设置一个值,指示是否获得了该锁。

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

参数

obj
Object

在其上获取锁的对象。

timeout
TimeSpan

用于等待锁的时间。 值为 -1 毫秒表示指定无限期等待。

lockTaken
Boolean

尝试获取锁的结果,通过引用传递。 输入必须为 false。 如果已获取锁,则输出为 true;否则输出为 false。 即使在尝试获取锁的过程中发生异常,也会设置输出。

例外

lockTaken 的输入为 true

obj 参数为 null

以毫秒为单位的 timeout 值为负,不等于 Infinite) (-1 毫秒,或大于 Int32.MaxValue

注解

如果转换为毫秒的参数 timeout 的值等于 -1,则此方法等效于 Enter(Object)。 如果 的值 timeout 等于 0,则此方法等效于 TryEnter(Object)

如果由于引发异常而未执行锁定,则为 lockTaken 参数指定的变量将在 false 此方法结束之后。 这允许程序在所有情况下确定是否需要释放锁。

备注

用于 Monitor 锁定对象 (即引用类型) ,而不是值类型。 有关详细信息,请参阅 Monitor 类主题。

若要确保线程不进入关键部分,应检查 的值 lockTaken ,并仅在关键节的值为 true时执行代码。 以下代码片段显示了用于调用此方法的模式。 请注意,应在块中finally调用Exit,以确保调用线程在发生异常时释放关键节上的锁。

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

另请参阅

适用于

.NET 9 和其他版本
产品 版本
.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
.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

在指定的毫秒数内尝试获取指定对象上的排他锁,并自动设置一个值,指示是否获取了该锁。

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

参数

obj
Object

在其上获取锁的对象。

millisecondsTimeout
Int32

等待锁所需的毫秒数。

lockTaken
Boolean

尝试获取锁的结果,通过引用传递。 输入必须为 false。 如果已获取锁,则输出为 true;否则输出为 false。 即使在尝试获取锁的过程中发生异常,也会设置输出。

例外

lockTaken 的输入为 true

obj 参数为 null

millisecondsTimeout 是负数且不等于 Infinite

示例

以下代码演示了使用 TryEnter(Object, Boolean) 方法重载的基本模式。 此重载始终设置传递给 ref Visual Basic) 中参数 (ByReflockTaken的变量的值,即使该方法引发异常,因此变量的值是测试是否必须释放锁的可靠方法。

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

注解

millisecondsTimeout如果 参数等于 Infinite,则此方法等效于 Enter(Object)。 如果 millisecondsTimeout 等于 0,则此方法等效于 TryEnter(Object)

如果由于引发异常而未执行锁定,则为 lockTaken 参数指定的变量将在 false 此方法结束之后。 这允许程序在所有情况下确定是否需要释放锁。

备注

用于 Monitor 锁定对象 (即引用类型) ,而不是值类型。 有关详细信息,请参阅 Monitor 类主题。

若要确保线程不进入关键部分,应检查 的值 lockTaken ,并仅在关键节的值为 true时执行代码。 以下代码片段显示了用于调用此方法的模式。 请注意,应在块中finally调用Exit,以确保调用线程在发生异常时释放关键节上的锁。

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

适用于

.NET 9 和其他版本
产品 版本
.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
.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

在指定的时间内尝试获取指定对象上的排他锁。

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

参数

obj
Object

在其上获取锁的对象。

timeout
TimeSpan

TimeSpan,表示等待锁所需的时间量。 值为 -1 毫秒表示指定无限期等待。

返回

如果当前线程获取该锁,则为 true;否则为 false

例外

obj 参数为 null

以毫秒为单位的 timeout 值为负,不等于 Infinite) (-1 毫秒,或大于 Int32.MaxValue

注解

如果转换为毫秒的参数 timeout 的值等于 -1,则此方法等效于 Enter。 如果 的值 timeout 等于 0,则此方法等效于 TryEnter

备注

用于 Monitor 锁定对象 (即引用类型) ,而不是值类型。 有关详细信息,请参阅 Monitor 类主题。

若要确保线程不进入关键部分,应检查方法的返回值,仅当其返回值为 true时,才在关键节中执行代码。 以下代码片段显示了用于调用此方法的模式。 请注意,应在块中finally调用Exit,以确保调用线程在发生异常时释放关键节上的锁。

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.
}

另请参阅

适用于

.NET 9 和其他版本
产品 版本
.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
.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

尝试获取指定对象上的排他锁,并自动设置一个值,指示是否获取了该锁。

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

参数

obj
Object

在其上获取锁的对象。

lockTaken
Boolean

尝试获取锁的结果,通过引用传递。 输入必须为 false。 如果已获取锁,则输出为 true;否则输出为 false。 即使在尝试获取锁的过程中发生异常,也会设置输出。

例外

lockTaken 的输入为 true

obj 参数为 null

示例

以下代码演示了使用 TryEnter(Object, Boolean) 方法重载的基本模式。 此重载始终设置传递给 ref Visual Basic) 中参数 (ByReflockTaken的变量的值,即使该方法引发异常,因此变量的值是测试是否必须释放锁的可靠方法。

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

注解

如果成功,此方法将获取 参数上的 obj 独占锁。 无论锁是否可用,此方法都会立即返回。

如果由于引发异常而未执行锁定,则为 lockTaken 参数指定的变量将在 false 此方法结束之后。 这允许程序在所有情况下确定是否需要释放锁。

此方法类似于 Enter(Object, Boolean),但它永远不会阻止当前线程。 如果线程无法在不阻止的情况下进入,则当方法返回时, lockTaken 参数设置为 false

备注

用于 Monitor 锁定对象 (即引用类型) ,而不是值类型。 有关详细信息,请参阅Monitor一文。

若要确保线程不进入关键部分,应检查 的值 lockTaken ,并仅在关键节的值为 true时执行代码。 以下代码片段显示了用于调用此方法的模式。 请注意,应在块中finally调用Exit,以确保调用线程在发生异常时释放关键节上的锁。

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

适用于

.NET 9 和其他版本
产品 版本
.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
.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

尝试获取指定对象的排他锁。

C#
public static bool TryEnter (object obj);

参数

obj
Object

在其上获取锁的对象。

返回

如果当前线程获取该锁,则为 true;否则为 false

例外

obj 参数为 null

示例

下面的代码示例演示如何使用 TryEnter 方法。

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
 */

注解

如果成功,此方法将获取 参数上的 obj 独占锁。 无论锁是否可用,此方法都会立即返回。

此方法类似于 Enter,但它永远不会阻止当前线程。 如果线程无法在不阻止的情况下进入,则 方法将 false,返回 。

备注

用于 Monitor 锁定对象 (即引用类型) ,而不是值类型。 有关详细信息,请参阅文章 Monitor

若要确保线程不进入关键部分,应检查方法的返回值,仅当其返回值为 true时,才在关键节中执行代码。 以下代码片段显示了用于调用此方法的模式。 请注意,应在块中finally调用Exit,以确保调用线程在发生异常时释放关键节上的锁。

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.
}

另请参阅

适用于

.NET 9 和其他版本
产品 版本
.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
.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

在指定的毫秒数内尝试获取指定对象上的排他锁。

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

参数

obj
Object

在其上获取锁的对象。

millisecondsTimeout
Int32

等待锁所需的毫秒数。

返回

如果当前线程获取该锁,则为 true;否则为 false

例外

obj 参数为 null

millisecondsTimeout 是负数且不等于 Infinite

注解

millisecondsTimeout如果 参数等于 Infinite,则此方法等效于 Enter。 如果 millisecondsTimeout 等于 0,则此方法等效于 TryEnter

备注

用于 Monitor 锁定对象 (即引用类型) ,而不是值类型。 有关详细信息,请参阅文章 Monitor

若要确保线程不进入关键部分,应检查方法的返回值,仅当其返回值为 true时,才在关键节中执行代码。 以下代码片段显示了用于调用此方法的模式。 请注意,应在块中finally调用Exit,以确保调用线程在发生异常时释放关键节上的锁。

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.
}

另请参阅

适用于

.NET 9 和其他版本
产品 版本
.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
.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