Monitor.TryEnter 메서드

정의

지정된 개체의 단독 잠금을 가져오려고 했습니다.Attempts to acquire an exclusive lock on the specified object.

오버로드

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)

지정된 시간 동안 지정된 개체의 단독 잠금을 가져오고 잠금 설정 여부를 나타내는 값을 자동으로 설정하려고 시도합니다.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.

public:
 static void TryEnter(System::Object ^ obj, TimeSpan timeout, bool % lockTaken);
public static void TryEnter (object obj, TimeSpan timeout, ref bool lockTaken);
static member TryEnter : obj * TimeSpan * bool -> unit
Public Shared Sub TryEnter (obj As Object, timeout As TimeSpan, ByRef lockTaken As Boolean)

매개 변수

obj
Object

잠금을 가져올 개체입니다.The object on which to acquire the lock.

timeout
TimeSpan

잠금을 대기할 시간입니다.The amount of time to wait for the lock. -1밀리초 값은 무한 대기를 지정합니다.A value of -1 millisecond specifies an infinite wait.

lockTaken
Boolean

잠금을 얻기 위한 시도의 결과로서, 참조에 의해 전달됩니다.The result of the attempt to acquire the lock, passed by reference. 입력은 false여야 합니다.The input must be false. 잠금을 얻으면 출력이 true이고, 그렇지 않으면 출력이 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.

예외

lockTaken에 대한 입력이 true인 경우The input to lockTaken is true.

obj 매개 변수가 null인 경우The obj parameter is null.

timeout 값(밀리초)이 음수이고 Infinite(-1밀리초)와 같지 않거나 MaxValue보다 큰 경우The value of timeout in milliseconds is negative and is not equal to Infinite (-1 millisecond), or is greater than MaxValue.

설명

timeout밀리초로 변환 된 매개 변수의 값이-1과 같으면이 메서드는와 동일 Enter(Object) 합니다.If the value of the timeout parameter converted to milliseconds equals -1, this method is equivalent to Enter(Object). 의 값 timeout 이 0 인 경우이 메서드는와 동일 TryEnter(Object) 합니다.If the value of timeout equals 0, this method is equivalent to TryEnter(Object).

예외가 throw 되어 잠금이 수행 되지 않은 경우 매개 변수에 대해 지정 된 변수는 lockTaken false 이 메서드가 종료 된 후입니다.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.

참고

를 사용 Monitor 하 여 값 형식이 아닌 개체 (참조 형식)를 잠급니다.Use Monitor to lock objects (that is, reference types), not value types. 자세한 내용은 클래스 항목을 참조 Monitor 하세요.For more information, see the Monitor class topic.

스레드가 임계 영역을 입력 하지 않도록 하려면 값을 검사 하 lockTaken 고 값이 인 경우에만 임계 영역에서 코드를 실행 해야 합니다 true .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. Exit finally 예외가 발생 하는 경우 호출 스레드가 임계 영역에 대 한 잠금을 해제 하도록 블록에서를 호출 해야 합니다.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.

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);
   }
}
Dim lockObj As New Object()
Dim timeout = TimeSpan.FromMilliseconds(500)
Dim lockTaken As Boolean = False

Try
   Monitor.TryEnter(lockObj, timeout, lockTaken)
   If lockTaken Then
      ' The critical section.
   Else
      ' The lock was not acquired.
   End If
Finally
   ' Ensure that the lock is released.
   If lockTaken Then Monitor.Exit(lockObj)
End Try

추가 정보

적용 대상

제품 도입

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.

public:
 static void TryEnter(System::Object ^ obj, int millisecondsTimeout, bool % lockTaken);
public static void TryEnter (object obj, int millisecondsTimeout, ref bool lockTaken);
static member TryEnter : obj * int * bool -> unit
Public Shared Sub TryEnter (obj As Object, millisecondsTimeout As Integer, ByRef lockTaken As Boolean)

매개 변수

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. 입력은 false여야 합니다.The input must be false. 잠금을 얻으면 출력이 true이고, 그렇지 않으면 출력이 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.

예외

lockTaken에 대한 입력이 true인 경우The input to lockTaken is true.

obj 매개 변수가 null인 경우The obj parameter is null.

millisecondsTimeout가 음수이고 Infinite가 아닌 경우millisecondsTimeout is negative, and not equal to Infinite.

예제

다음 코드에서는 메서드 오버 로드를 사용 하기 위한 기본 패턴을 보여 줍니다 TryEnter(Object, Boolean) .The following code shows the basic pattern for using the TryEnter(Object, Boolean) method overload. 이 오버 로드는 메서드가 예외를 throw 하는 경우 Visual Basic에도 매개 변수에 전달 되는 변수의 값을 항상 설정 ref ByRef lockTaken 하므로 변수의 값은 잠금이 해제 되어야 하는지 여부를 테스트 하는 신뢰할 수 있는 방법입니다.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.

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);
    }
}
Dim acquiredLock As Boolean = False

Try
    Monitor.TryEnter(lockObject, 500, acquiredLock)
    If acquiredLock Then

        ' Code that accesses resources that are protected by the lock.

    Else

        ' Code to deal with the fact that the lock was not acquired.

    End If
Finally
    If acquiredLock Then
        Monitor.Exit(lockObject)
    End If
End Try

설명

millisecondsTimeout매개 변수가 이면 Infinite 이 메서드는와 동일 Enter(Object) 합니다.If the millisecondsTimeout parameter equals Infinite, this method is equivalent to Enter(Object). millisecondsTimeout가 0과 같으면이 메서드는와 동일 TryEnter(Object) 합니다.If millisecondsTimeout equals 0, this method is equivalent to TryEnter(Object).

예외가 throw 되어 잠금이 수행 되지 않은 경우 매개 변수에 대해 지정 된 변수는 lockTaken false 이 메서드가 종료 된 후입니다.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.

참고

를 사용 Monitor 하 여 값 형식이 아닌 개체 (참조 형식)를 잠급니다.Use Monitor to lock objects (that is, reference types), not value types. 자세한 내용은 클래스 항목을 참조 Monitor 하세요.For more information, see the Monitor class topic.

스레드가 임계 영역을 입력 하지 않도록 하려면 값을 검사 하 lockTaken 고 값이 인 경우에만 임계 영역에서 코드를 실행 해야 합니다 true .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. Exit finally 예외가 발생 하는 경우 호출 스레드가 임계 영역에 대 한 잠금을 해제 하도록 블록에서를 호출 해야 합니다.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.

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);
   }   
}
Dim lockObj As New Object()
Dim timeout As Integer = 500
Dim lockTaken As Boolean = False

Try
   Monitor.TryEnter(lockObj, timeout, lockTaken)
   If lockTaken Then
      ' The critical section.
   Else
      ' The lock was not acquired.
   End If
Finally
   ' Ensure that the lock is released.
   If lockTaken Then Monitor.Exit(lockObj)
End Try

적용 대상

제품 도입

TryEnter(Object, TimeSpan)

지정된 시간 동안 지정된 개체의 단독 잠금을 가져오려고 했습니다.Attempts, for the specified amount of time, to acquire an exclusive lock on the specified object.

public:
 static bool TryEnter(System::Object ^ obj, TimeSpan timeout);
public static bool TryEnter (object obj, TimeSpan timeout);
static member TryEnter : obj * TimeSpan -> bool
Public Shared Function TryEnter (obj As Object, timeout As TimeSpan) As Boolean

매개 변수

obj
Object

잠금을 가져올 개체입니다.The object on which to acquire the lock.

timeout
TimeSpan

잠금을 기다리는 시간을 나타내는 TimeSpan입니다.A TimeSpan representing the amount of time to wait for the lock. -1밀리초 값은 무한 대기를 지정합니다.A value of -1 millisecond specifies an infinite wait.

반환

Boolean

현재 스레드에서 잠금을 가져오면 true이고, 그렇지 않으면 false입니다.true if the current thread acquires the lock; otherwise, false.

예외

obj 매개 변수가 null인 경우The obj parameter is null.

timeout 값(밀리초)이 음수이고 Infinite(-1밀리초)와 같지 않거나 MaxValue보다 큰 경우The value of timeout in milliseconds is negative and is not equal to Infinite (-1 millisecond), or is greater than MaxValue.

설명

timeout밀리초로 변환 된 매개 변수의 값이-1과 같으면이 메서드는와 동일 Enter 합니다.If the value of the timeout parameter converted to milliseconds equals -1, this method is equivalent to Enter. 의 값 timeout 이 0 인 경우이 메서드는와 동일 TryEnter 합니다.If the value of timeout equals 0, this method is equivalent to TryEnter.

참고

를 사용 Monitor 하 여 값 형식이 아닌 개체 (참조 형식)를 잠급니다.Use Monitor to lock objects (that is, reference types), not value types. 자세한 내용은 Monitor 클래스 항목을 참조 하세요.For details, see the Monitor class topic.

스레드가 임계 영역을 입력 하지 않도록 하려면 메서드의 반환 값을 검사 하 고 반환 값이 인 경우에만 임계 영역에서 코드를 실행 해야 합니다 true .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. Exit finally 예외가 발생 하는 경우 호출 스레드가 임계 영역에 대 한 잠금을 해제 하도록 블록에서를 호출 해야 합니다.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.

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.
}
Dim lockObj As New Object()
Dim timeout = TimeSpan.FromMilliseconds(500)

If Monitor.TryEnter(lockObj, timeout) Then
   Try
      ' The critical section.
   Finally
      ' Ensure that the lock is released.
      Monitor.Exit(lockObj)
   End Try
Else
   ' The lock was not acquired.
End If

추가 정보

적용 대상

제품 도입

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.

public:
 static void TryEnter(System::Object ^ obj, bool % lockTaken);
public static void TryEnter (object obj, ref bool lockTaken);
static member TryEnter : obj * bool -> unit
Public Shared Sub TryEnter (obj As Object, ByRef lockTaken As Boolean)

매개 변수

obj
Object

잠금을 가져올 개체입니다.The object on which to acquire the lock.

lockTaken
Boolean

잠금을 얻기 위한 시도의 결과로서, 참조에 의해 전달됩니다.The result of the attempt to acquire the lock, passed by reference. 입력은 false여야 합니다.The input must be false. 잠금을 얻으면 출력이 true이고, 그렇지 않으면 출력이 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.

예외

lockTaken에 대한 입력이 true인 경우The input to lockTaken is true.

obj 매개 변수가 null인 경우The obj parameter is null.

예제

다음 코드에서는 메서드 오버 로드를 사용 하기 위한 기본 패턴을 보여 줍니다 TryEnter(Object, Boolean) .The following code shows the basic pattern for using the TryEnter(Object, Boolean) method overload. 이 오버 로드는 메서드가 예외를 throw 하는 경우 Visual Basic에도 매개 변수에 전달 되는 변수의 값을 항상 설정 ref ByRef lockTaken 하므로 변수의 값은 잠금이 해제 되어야 하는지 여부를 테스트 하는 신뢰할 수 있는 방법입니다.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.

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);
    }
}
Dim acquiredLock As Boolean = False

Try
    Monitor.TryEnter(lockObject, acquiredLock)
    If acquiredLock Then

        ' Code that accesses resources that are protected by the lock.

    Else

        ' Code to deal with the fact that the lock was not acquired.

    End If
Finally
    If acquiredLock Then
        Monitor.Exit(lockObject)
    End If
End Try

설명

성공 하면이 메서드는 매개 변수에 대 한 배타적 잠금을 획득 obj 합니다.If successful, this method acquires an exclusive lock on the obj parameter. 잠금을 사용할 수 있는지 여부에 관계 없이이 메서드는 즉시 반환 됩니다.This method returns immediately, whether or not the lock is available.

예외가 throw 되어 잠금이 수행 되지 않은 경우 매개 변수에 대해 지정 된 변수는 lockTaken false 이 메서드가 종료 된 후입니다.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.

이 메서드는와 유사 Enter(Object, Boolean) 하지만 현재 스레드를 차단 하지는 않습니다.This method is similar to Enter(Object, Boolean), but it will never block the current thread. 차단 없이 스레드를 입력할 수 없으면 lockTaken false 메서드가 반환 될 때 인수가로 설정 됩니다.If the thread cannot enter without blocking, the lockTaken argument is set to false when the method returns.

참고

를 사용 Monitor 하 여 값 형식이 아닌 개체 (참조 형식)를 잠급니다.Use Monitor to lock objects (that is, reference types), not value types. 자세한 내용은 문서를 참조 Monitor 하세요.For more information, see the Monitor article.

스레드가 임계 영역을 입력 하지 않도록 하려면 값을 검사 하 lockTaken 고 값이 인 경우에만 임계 영역에서 코드를 실행 해야 합니다 true .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. Exit finally 예외가 발생 하는 경우 호출 스레드가 임계 영역에 대 한 잠금을 해제 하도록 블록에서를 호출 해야 합니다.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.

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);
   }
}
Dim lockObj As New Object()
Dim lockTaken As Boolean = False

Try 
   Monitor.TryEnter(lockObj, lockTaken) 
   If lockTaken Then
      ' The critical section.
   Else 
      ' The lock was not acquired.
   End If
Finally 
   ' Ensure that the lock is released.
   If lockTaken Then Monitor.Exit(lockObj)
End Try

적용 대상

제품 도입

TryEnter(Object)

지정된 개체의 단독 잠금을 가져오려고 했습니다.Attempts to acquire an exclusive lock on the specified object.

public:
 static bool TryEnter(System::Object ^ obj);
public static bool TryEnter (object obj);
static member TryEnter : obj -> bool
Public Shared Function TryEnter (obj As Object) As Boolean

매개 변수

obj
Object

잠금을 가져올 개체입니다.The object on which to acquire the lock.

반환

Boolean

현재 스레드에서 잠금을 가져오면 true이고, 그렇지 않으면 false입니다.true if the current thread acquires the lock; otherwise, false.

예외

obj 매개 변수가 null인 경우The obj parameter is null.

예제

다음 코드 예제에서는 TryEnter 메서드를 사용하는 방법을 보여 줍니다.The following code example demonstrates how to use the TryEnter method.

#using <System.dll>

using namespace System;
using namespace System::Threading;
using namespace System::Collections::Generic;
using namespace System::Text;

generic <typename T> public ref class SafeQueue
{
private:
   // A queue that is protected by Monitor.
   Queue<T>^ m_inputQueue;

public:
   SafeQueue()
   {
      m_inputQueue = gcnew Queue<T>();
   };

   // Lock the queue and add an element.
   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.
   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.
   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.
   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.
   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.
   String^ PrintAllElements()
   {
      StringBuilder^ output = gcnew StringBuilder();

      // Lock the queue.
      Monitor::Enter(m_inputQueue);
      try
      {
         for each ( 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 ref class Example
{
private:
   static SafeQueue<int>^ q = gcnew SafeQueue<int>();
   static int threadsRunning = 0;
   static array<array<int>^>^ results = gcnew array<array<int>^>(3);

   static void ThreadProc(Object^ state)
   {
      DateTime finish = DateTime::Now.AddSeconds(10);
      Random^ rand = gcnew Random();
      array<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 (Exception^ ex)
            {
               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(threadsRunning))      
      {
         StringBuilder^ sb = gcnew 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());
      }
   };

   static array<String^>^ titles = {
      "Enqueue                       ", 
      "TryEnqueue succeeded          ", 
      "TryEnqueue failed             ", 
      "TryEnqueue(T, wait) succeeded ", 
      "TryEnqueue(T, wait) failed    ", 
      "Dequeue attempts              ", 
      "Dequeue exceptions            ", 
      "Remove operations             ", 
      "Queue elements removed        "};

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

public:
   static void Demo()
   {
      Console::WriteLine("Working...");

      for(int i = 0; i < 3; i++)
      {
         Thread^ t = gcnew Thread(gcnew ParameterizedThreadStart(Example::ThreadProc));
         t->Start(i);
         Interlocked::Increment(threadsRunning);
      }
   };
};

void main()
{
   Example::Demo();
}


/* This example produces output similar to the following:

Working...
                               Thread 1 Thread 2 Thread 3    Total
Enqueue                          274718   513514   337895  1126127
TryEnqueue succeeded             274502   513516   337480  1125498
TryEnqueue failed                   119      235      141      495
TryEnqueue(T, wait) succeeded    274552   513116   338532  1126200
TryEnqueue(T, wait) failed            0        1        0        1
Dequeue attempts                 824038  1541866  1015006  3380910
Dequeue exceptions                12828    23416    14799    51043
Remove operations                 68746   128218    84306   281270
Queue elements removed            11464    22024    14470    47958
Queue elements removed            2921     4690     2982    10593
 */
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
 */
Imports System.Threading
Imports System.Collections.Generic
Imports System.Text

Class SafeQueue(Of T)

   ' A queue that is protected by Monitor.
   Private m_inputQueue As New Queue(Of T)

   ' Lock the queue and add an element.
   Public Sub Enqueue(ByVal qValue As T)

      ' 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)
      End Try
   End Sub

   ' 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 becomes available during the specified time
   ' interval.
   Public Function TryEnqueue(ByVal qValue As T, ByVal waitTime As Integer) As Boolean

      ' Request the lock.
      If Monitor.TryEnter(m_inputQueue, waitTime) 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

   ' Lock the queue and dequeue an element.
   Public Function Dequeue() As T

      Dim retval As T

      ' 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)
      End Try

      Return retval
   End Function

   ' Delete all elements that equal the given object.
   Public Function Remove(ByVal qValue As T) As Integer

      Dim removedCt As Integer = 0

      ' Wait until the lock is available and lock the queue.
      Monitor.Enter(m_inputQueue)
      Try
         Dim counter As Integer = m_inputQueue.Count
         While (counter > 0)
            'Check each element.
            Dim elem As T = m_inputQueue.Dequeue()
            If Not elem.Equals(qValue) Then
               m_inputQueue.Enqueue(elem)
            Else
               ' Keep a count of items removed.
               removedCt += 1
            End If
            counter = counter - 1
         End While

      Finally
         ' Ensure that the lock is released.
         Monitor.Exit(m_inputQueue)
      End Try

      Return removedCt
   End Function

   ' Print all queue elements.
   Public Function PrintAllElements() As String

      Dim output As New StringBuilder()

      'Lock the queue.
      Monitor.Enter(m_inputQueue)
      Try
         For Each elem As T In m_inputQueue
            ' Print the next element.
            output.AppendLine(elem.ToString())
         Next

      Finally
         ' Ensure that the lock is released.
         Monitor.Exit(m_inputQueue)
      End Try

      Return output.ToString()
   End Function
End Class

Public Class Example

   Private Shared q As New SafeQueue(Of Integer)
   Private Shared threadsRunning As Integer = 0
   Private Shared results(2)() As Integer

   Friend Shared Sub Main()

      Console.WriteLine("Working...")

      For i As Integer = 0 To 2

         Dim t As New Thread(AddressOf ThreadProc)
         t.Start(i)
         Interlocked.Increment(threadsRunning)

      Next i

   End Sub

   Private Shared Sub ThreadProc(ByVal state As Object)

      Dim finish As DateTime = DateTime.Now.AddSeconds(10)
      Dim rand As New Random()
      Dim result() As Integer = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }
      Dim threadNum As Integer = CInt(state)

      While (DateTime.Now < finish)

         Dim what As Integer = rand.Next(250)
         Dim how As Integer = rand.Next(100)

         If how < 16 Then
            q.Enqueue(what)
            result(ThreadResultIndex.EnqueueCt) += 1
         Else If how < 32 Then
            If q.TryEnqueue(what)
               result(ThreadResultIndex.TryEnqueueSucceedCt) += 1
            Else
               result(ThreadResultIndex.TryEnqueueFailCt) += 1
            End If
         Else If how < 48 Then
            ' Even a very small wait significantly increases the success 
            ' rate of the conditional enqueue operation.
            If q.TryEnqueue(what, 10)
               result(ThreadResultIndex.TryEnqueueWaitSucceedCt) += 1
            Else
               result(ThreadResultIndex.TryEnqueueWaitFailCt) += 1
            End If
         Else If how < 96 Then
            result(ThreadResultIndex.DequeueCt) += 1
            Try
               q.Dequeue()
            Catch
               result(ThreadResultIndex.DequeueExCt) += 1
            End Try
         Else
            result(ThreadResultIndex.RemoveCt) += 1
            result(ThreadResultIndex.RemovedCt) += q.Remove(what)
         End If
         
      End While

      results(threadNum) = result

      If 0 = Interlocked.Decrement(threadsRunning) Then
      
         Dim sb As New StringBuilder( _
            "                               Thread 1 Thread 2 Thread 3    Total" & vbLf)

         For row As Integer = 0 To 8

            Dim total As Integer = 0
            sb.Append(titles(row))

            For col As Integer = 0 To 2

               sb.Append(String.Format("{0,9}", results(col)(row)))
               total += results(col)(row)

            Next col

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

         Next row

         Console.WriteLine(sb.ToString())

      End If     
    
   End Sub

   Private Shared titles() As String = { _
      "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
   End Enum

End Class

' This example produces output similar to the following:
'
'Working...
'                               Thread 1 Thread 2 Thread 3    Total
'Enqueue                          294357   512164   302838  1109359
'TryEnqueue succeeded             294486   512403   303117  1110006
'TryEnqueue failed                   108      234      127      469
'TryEnqueue(T, wait) succeeded    294259   512796   302556  1109611
'TryEnqueue(T, wait) failed            1        1        1        3
'Dequeue attempts                 882266  1537993   907795  3328054
'Dequeue exceptions                12691    21474    13480    47645
'Remove operations                 74059   128715    76187   278961
'Queue elements removed            12667    22606    13219    48492

설명

성공 하면이 메서드는 매개 변수에 대 한 배타적 잠금을 획득 obj 합니다.If successful, this method acquires an exclusive lock on the obj parameter. 잠금을 사용할 수 있는지 여부에 관계 없이이 메서드는 즉시 반환 됩니다.This method returns immediately, whether or not the lock is available.

이 메서드는와 유사 Enter 하지만 현재 스레드를 차단 하지는 않습니다.This method is similar to Enter, but it will never block the current thread. 스레드가 차단 없이 입력 될 수 없는 경우 메서드는을 반환 합니다 false, .If the thread cannot enter without blocking, the method returns false,.

참고

를 사용 Monitor 하 여 값 형식이 아닌 개체 (참조 형식)를 잠급니다.Use Monitor to lock objects (that is, reference types), not value types. 자세한 내용은 문서를 참조 Monitor 하세요.For details, see the Monitor article.

스레드가 임계 영역을 입력 하지 않도록 하려면 메서드의 반환 값을 검사 하 고 반환 값이 인 경우에만 임계 영역에서 코드를 실행 해야 합니다 true .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. Exit finally 예외가 발생 하는 경우 호출 스레드가 임계 영역에 대 한 잠금을 해제 하도록 블록에서를 호출 해야 합니다.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.

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.
}
Dim lockObj As New Object()

If Monitor.TryEnter(lockObj) Then
   Try
      ' The critical section.
   Finally
      ' Ensure that the lock is released.
      Monitor.Exit(lockObj)
   End Try
Else
   ' The lock was not acquired.
End If

추가 정보

적용 대상

제품 도입

TryEnter(Object, Int32)

지정된 시간(밀리초) 동안 지정된 개체의 단독 잠금을 가져오려고 했습니다.Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object.

public:
 static bool TryEnter(System::Object ^ obj, int millisecondsTimeout);
public static bool TryEnter (object obj, int millisecondsTimeout);
static member TryEnter : obj * int -> bool
Public Shared Function TryEnter (obj As Object, millisecondsTimeout As Integer) As Boolean

매개 변수

obj
Object

잠금을 가져올 개체입니다.The object on which to acquire the lock.

millisecondsTimeout
Int32

잠금을 기다릴 밀리초 수입니다.The number of milliseconds to wait for the lock.

반환

Boolean

현재 스레드에서 잠금을 가져오면 true이고, 그렇지 않으면 false입니다.true if the current thread acquires the lock; otherwise, false.

예외

obj 매개 변수가 null인 경우The obj parameter is null.

millisecondsTimeout가 음수이고 Infinite가 아닌 경우millisecondsTimeout is negative, and not equal to Infinite.

설명

millisecondsTimeout매개 변수가 이면 Infinite 이 메서드는와 동일 Enter 합니다.If the millisecondsTimeout parameter equals Infinite, this method is equivalent to Enter. millisecondsTimeout가 0과 같으면이 메서드는와 동일 TryEnter 합니다.If millisecondsTimeout equals 0, this method is equivalent to TryEnter.

참고

를 사용 Monitor 하 여 값 형식이 아닌 개체 (참조 형식)를 잠급니다.Use Monitor to lock objects (that is, reference types), not value types. 자세한 내용은 문서를 참조 Monitor 하세요.For details, see the Monitor article.

스레드가 임계 영역을 입력 하지 않도록 하려면 메서드의 반환 값을 검사 하 고 반환 값이 인 경우에만 임계 영역에서 코드를 실행 해야 합니다 true .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. Exit finally 예외가 발생 하는 경우 호출 스레드가 임계 영역에 대 한 잠금을 해제 하도록 블록에서를 호출 해야 합니다.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.

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.
}
Dim lockObj As New Object()
Dim timeout As Integer = 500

If Monitor.TryEnter(lockObj, timeout) Then
   Try
      ' The critical section.
   Finally
      ' Ensure that the lock is released.
      Monitor.Exit(lockObj)
   End Try
Else
   ' The lock was not acquired.
End If

추가 정보

적용 대상

제품 도입