Monitor 類別

定義

提供一套機制,同步處理物件的存取。Provides a mechanism that synchronizes access to objects.

public ref class Monitor abstract sealed
[System.Runtime.InteropServices.ComVisible(true)]
public static class Monitor
type Monitor = class
Public Class Monitor
繼承
Monitor
屬性

範例

下列範例會使用Monitor類別來同步存取Random由類別所表示之亂數字產生器的單一實例。The following example uses the Monitor class to synchronize access to a single instance of a random number generator represented by the Random class. 此範例會建立十個工作,其中每一個都會線上程集區執行緒上以非同步方式執行。The example creates ten tasks, each of which executes asynchronously on a thread pool thread. 每項工作都會產生10000亂數、計算其平均值,並更新兩個程式層級的變數,以維持產生的亂數字總數和其總和。Each task generates 10,000 random numbers, calculates their average, and updates two procedure-level variables that maintain a running total of the number of random numbers generated and their sum. 執行完所有工作之後,就會使用這兩個值來計算整體平均值。After all tasks have executed, these two values are then used to calculate the overall mean.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      List<Task> tasks = new List<Task>();
      Random rnd = new Random();
      long total = 0;
      int n = 0;
      
      for (int taskCtr = 0; taskCtr < 10; taskCtr++)
         tasks.Add(Task.Run( () => {  int[] values = new int[10000];
                                      int taskTotal = 0;
                                      int taskN = 0;
                                      int ctr = 0;
                                      Monitor.Enter(rnd);
                                         // Generate 10,000 random integers
                                         for (ctr = 0; ctr < 10000; ctr++)
                                            values[ctr] = rnd.Next(0, 1001);
                                      Monitor.Exit(rnd);
                                      taskN = ctr;
                                      foreach (var value in values)
                                         taskTotal += value;

                                      Console.WriteLine("Mean for task {0,2}: {1:N2} (N={2:N0})",
                                                        Task.CurrentId, (taskTotal * 1.0)/taskN,
                                                        taskN);
                                      Interlocked.Add(ref n, taskN);
                                      Interlocked.Add(ref total, taskTotal);
                                    } ));
      try {
         Task.WaitAll(tasks.ToArray());
         Console.WriteLine("\nMean for all tasks: {0:N2} (N={1:N0})",
                           (total * 1.0)/n, n);

      }
      catch (AggregateException e) {
         foreach (var ie in e.InnerExceptions)
            Console.WriteLine("{0}: {1}", ie.GetType().Name, ie.Message);
      }
   }
}
// The example displays output like the following:
//       Mean for task  1: 499.04 (N=10,000)
//       Mean for task  2: 500.42 (N=10,000)
//       Mean for task  3: 499.65 (N=10,000)
//       Mean for task  8: 502.59 (N=10,000)
//       Mean for task  5: 502.75 (N=10,000)
//       Mean for task  4: 494.88 (N=10,000)
//       Mean for task  7: 499.22 (N=10,000)
//       Mean for task 10: 496.45 (N=10,000)
//       Mean for task  6: 499.75 (N=10,000)
//       Mean for task  9: 502.79 (N=10,000)
//
//       Mean for all tasks: 499.75 (N=100,000)
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tasks As New List(Of Task)()
      Dim rnd As New Random()
      Dim total As Long = 0
      Dim n As Integer = 0

      For taskCtr As Integer = 0 To 9
         tasks.Add(Task.Run( Sub()
                                Dim values(9999) As Integer
                                Dim taskTotal As Integer = 0
                                Dim taskN As Integer = 0
                                Dim ctr As Integer = 0
                                Monitor.Enter(rnd)
                                   ' Generate 10,000 random integers.
                                    For ctr = 0 To 9999
                                       values(ctr) = rnd.Next(0, 1001)
                                    Next
                                Monitor.Exit(rnd)
                                taskN = ctr
                                For Each value in values
                                   taskTotal += value
                                Next
                                    
                                Console.WriteLine("Mean for task {0,2}: {1:N2} (N={2:N0})",
                                                  Task.CurrentId, taskTotal/taskN,
                                                  taskN)
                                Interlocked.Add(n, taskN)
                                Interlocked.Add(total, taskTotal)
                             End Sub ))
      Next
      
      Try
         Task.WaitAll(tasks.ToArray())
         Console.WriteLine()
         Console.WriteLine("Mean for all tasks: {0:N2} (N={1:N0})",
                           (total * 1.0)/n, n)
      Catch e As AggregateException
         For Each ie In e.InnerExceptions
            Console.WriteLine("{0}: {1}", ie.GetType().Name, ie.Message)
         Next
      End Try
   End Sub
End Module
' The example displays output like the following:
'       Mean for task  1: 499.04 (N=10,000)
'       Mean for task  2: 500.42 (N=10,000)
'       Mean for task  3: 499.65 (N=10,000)
'       Mean for task  8: 502.59 (N=10,000)
'       Mean for task  5: 502.75 (N=10,000)
'       Mean for task  4: 494.88 (N=10,000)
'       Mean for task  7: 499.22 (N=10,000)
'       Mean for task 10: 496.45 (N=10,000)
'       Mean for task  6: 499.75 (N=10,000)
'       Mean for task  9: 502.79 (N=10,000)
'
'       Mean for all tasks: 499.75 (N=100,000)

因為它們可以從執行緒集區執行緒上執行的任何工作存取,所以存取變數totaln也必須同步處理。Because they can be accessed from any task running on a thread pool thread, access to the variables total and n must also be synchronized. Interlocked.Add方法用於此用途。The Interlocked.Add method is used for this purpose.

Monitor下列範例示範類別( Interlocked SyncLock lock以或語言AutoResetEvent結構實)、類別和類別的結合用法。The following example demonstrates the combined use of the Monitor class (implemented with the lock or SyncLock language construct), the Interlocked class, and the AutoResetEvent class. 它會定義兩個 internal (在 C# 中) 或 Friend (在 Visual Basic 中) 類別 SyncResourceUnSyncResource,分別提供對資源的同步存取和非同步存取。It defines two internal (in C#) or Friend (in Visual Basic) classes, SyncResource and UnSyncResource, that respectively provide synchronized and unsynchronized access to a resource. 為了確保範例說明同步存取和非同步存取 (如果每個方法呼叫都迅速完成則可能發生這種情況) 之間的差異,這個方法會包含隨機延遲:針對其 Thread.ManagedThreadId 屬性為偶數的執行緒,這個方法會呼叫 Thread.Sleep 以引入 2,000 毫秒的延遲。To ensure that the example illustrates the difference between the synchronized and unsynchronized access (which could be the case if each method call completes rapidly), the method includes a random delay: for threads whose Thread.ManagedThreadId property is even, the method calls Thread.Sleep to introduce a delay of 2,000 milliseconds. 請注意,由於 SyncResource 類別不是公用的,因此不會有任何用戶端程式碼在同步處理的資源上取得鎖定;內部類別本身會取得鎖定。Note that, because the SyncResource class is not public, none of the client code takes a lock on the synchronized resource; the internal class itself takes the lock. 這可防止惡意程式碼在公開物件上取得鎖定。This prevents malicious code from taking a lock on a public object.

using System;
using System.Threading;

internal class SyncResource
{
    // Use a monitor to enforce synchronization.
    public void Access()
    {
        lock(this) {
            Console.WriteLine("Starting synchronized resource access on thread #{0}",
                              Thread.CurrentThread.ManagedThreadId);
            if (Thread.CurrentThread.ManagedThreadId % 2 == 0)
                Thread.Sleep(2000);

            Thread.Sleep(200);
            Console.WriteLine("Stopping synchronized resource access on thread #{0}",
                              Thread.CurrentThread.ManagedThreadId);
        }
    }
}

internal class UnSyncResource
{
    // Do not enforce synchronization.
    public void Access()
    {
        Console.WriteLine("Starting unsynchronized resource access on Thread #{0}",
                          Thread.CurrentThread.ManagedThreadId);
        if (Thread.CurrentThread.ManagedThreadId % 2 == 0)
            Thread.Sleep(2000);

        Thread.Sleep(200);
        Console.WriteLine("Stopping unsynchronized resource access on thread #{0}",
                          Thread.CurrentThread.ManagedThreadId);
    }
}

public class App
{
    private static int numOps;
    private static AutoResetEvent opsAreDone = new AutoResetEvent(false);
    private static SyncResource SyncRes = new SyncResource();
    private static UnSyncResource UnSyncRes = new UnSyncResource();

   public static void Main()
   {
        // Set the number of synchronized calls.
        numOps = 5;
        for (int ctr = 0; ctr <= 4; ctr++)
            ThreadPool.QueueUserWorkItem(new WaitCallback(SyncUpdateResource));

        // Wait until this WaitHandle is signaled.
        opsAreDone.WaitOne();
        Console.WriteLine("\t\nAll synchronized operations have completed.\n");

        // Reset the count for unsynchronized calls.
        numOps = 5;
        for (int ctr = 0; ctr <= 4; ctr++)
            ThreadPool.QueueUserWorkItem(new WaitCallback(UnSyncUpdateResource));

        // Wait until this WaitHandle is signaled.
        opsAreDone.WaitOne();
        Console.WriteLine("\t\nAll unsynchronized thread operations have completed.\n");
   }

    static void SyncUpdateResource(Object state)
    {
        // Call the internal synchronized method.
        SyncRes.Access();

        // Ensure that only one thread can decrement the counter at a time.
        if (Interlocked.Decrement(ref numOps) == 0)
            // Announce to Main that in fact all thread calls are done.
            opsAreDone.Set();
    }

    static void UnSyncUpdateResource(Object state)
    {
        // Call the unsynchronized method.
        UnSyncRes.Access();

        // Ensure that only one thread can decrement the counter at a time.
        if (Interlocked.Decrement(ref numOps) == 0)
            // Announce to Main that in fact all thread calls are done.
            opsAreDone.Set();
    }
}
// The example displays output like the following:
//    Starting synchronized resource access on thread #6
//    Stopping synchronized resource access on thread #6
//    Starting synchronized resource access on thread #7
//    Stopping synchronized resource access on thread #7
//    Starting synchronized resource access on thread #3
//    Stopping synchronized resource access on thread #3
//    Starting synchronized resource access on thread #4
//    Stopping synchronized resource access on thread #4
//    Starting synchronized resource access on thread #5
//    Stopping synchronized resource access on thread #5
//
//    All synchronized operations have completed.
//
//    Starting unsynchronized resource access on Thread #7
//    Starting unsynchronized resource access on Thread #9
//    Starting unsynchronized resource access on Thread #10
//    Starting unsynchronized resource access on Thread #6
//    Starting unsynchronized resource access on Thread #3
//    Stopping unsynchronized resource access on thread #7
//    Stopping unsynchronized resource access on thread #9
//    Stopping unsynchronized resource access on thread #3
//    Stopping unsynchronized resource access on thread #10
//    Stopping unsynchronized resource access on thread #6
//
//    All unsynchronized thread operations have completed.
Imports System.Threading

Friend Class SyncResource
    ' Use a monitor to enforce synchronization.
    Public Sub Access()
        SyncLock Me
            Console.WriteLine("Starting synchronized resource access on thread #{0}",
                              Thread.CurrentThread.ManagedThreadId)
            If Thread.CurrentThread.ManagedThreadId Mod 2 = 0 Then
                Thread.Sleep(2000)
            End If
            Thread.Sleep(200)
            Console.WriteLine("Stopping synchronized resource access on thread #{0}",
                              Thread.CurrentThread.ManagedThreadId)
        End SyncLock
    End Sub
End Class

Friend Class UnSyncResource
    ' Do not enforce synchronization.
    Public Sub Access()
        Console.WriteLine("Starting unsynchronized resource access on Thread #{0}",
                          Thread.CurrentThread.ManagedThreadId)
        If Thread.CurrentThread.ManagedThreadId Mod 2 = 0 Then
            Thread.Sleep(2000)
        End If
        Thread.Sleep(200)
        Console.WriteLine("Stopping unsynchronized resource access on thread #{0}",
                          Thread.CurrentThread.ManagedThreadId)
    End Sub
End Class

Public Module App
    Private numOps As Integer
    Private opsAreDone As New AutoResetEvent(False)
    Private SyncRes As New SyncResource()
    Private UnSyncRes As New UnSyncResource()

    Public Sub Main()
        ' Set the number of synchronized calls.
        numOps = 5
        For ctr As Integer = 0 To 4
            ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf SyncUpdateResource))
        Next
        ' Wait until this WaitHandle is signaled.
        opsAreDone.WaitOne()
        Console.WriteLine(vbTab + vbNewLine + "All synchronized operations have completed.")
        Console.WriteLine()

        numOps = 5
        ' Reset the count for unsynchronized calls.
        For ctr As Integer = 0 To 4
            ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf UnSyncUpdateResource))
        Next

        ' Wait until this WaitHandle is signaled.
        opsAreDone.WaitOne()
        Console.WriteLine(vbTab + vbNewLine + "All unsynchronized thread operations have completed.")
    End Sub

    Sub SyncUpdateResource()
        ' Call the internal synchronized method.
        SyncRes.Access()

        ' Ensure that only one thread can decrement the counter at a time.
        If Interlocked.Decrement(numOps) = 0 Then
            ' Announce to Main that in fact all thread calls are done.
            opsAreDone.Set()
        End If
    End Sub

    Sub UnSyncUpdateResource()
        ' Call the unsynchronized method.
        UnSyncRes.Access()

        ' Ensure that only one thread can decrement the counter at a time.
        If Interlocked.Decrement(numOps) = 0 Then
            ' Announce to Main that in fact all thread calls are done.
            opsAreDone.Set()
        End If
    End Sub
End Module
' The example displays output like the following:
'    Starting synchronized resource access on thread #6
'    Stopping synchronized resource access on thread #6
'    Starting synchronized resource access on thread #7
'    Stopping synchronized resource access on thread #7
'    Starting synchronized resource access on thread #3
'    Stopping synchronized resource access on thread #3
'    Starting synchronized resource access on thread #4
'    Stopping synchronized resource access on thread #4
'    Starting synchronized resource access on thread #5
'    Stopping synchronized resource access on thread #5
'
'    All synchronized operations have completed.
'
'    Starting unsynchronized resource access on Thread #7
'    Starting unsynchronized resource access on Thread #9
'    Starting unsynchronized resource access on Thread #10
'    Starting unsynchronized resource access on Thread #6
'    Starting unsynchronized resource access on Thread #3
'    Stopping unsynchronized resource access on thread #7
'    Stopping unsynchronized resource access on thread #9
'    Stopping unsynchronized resource access on thread #3
'    Stopping unsynchronized resource access on thread #10
'    Stopping unsynchronized resource access on thread #6
'
'    All unsynchronized thread operations have completed.

這個範例會定義變數 numOps,以定義將會嘗試存取資源的執行緒數目。The example defines a variable, numOps, that defines the number of threads that will attempt to access the resource. 應用程式執行緒會針對同步存取和非同步存取各呼叫 ThreadPool.QueueUserWorkItem(WaitCallback) 方法五次。The application thread calls the ThreadPool.QueueUserWorkItem(WaitCallback) method for synchronized and unsynchronized access five times each. ThreadPool.QueueUserWorkItem(WaitCallback) 方法具有單一參數和不接受任何參數的一個委派,並且不會傳回任何值。The ThreadPool.QueueUserWorkItem(WaitCallback) method has a single parameter, a delegate that accepts no parameters and returns no value. 針對同步存取,它會叫用 SyncUpdateResource 方法;針對未同步存取,它會叫用 UnSyncUpdateResource 方法。For synchronized access, it invokes the SyncUpdateResource method; for unsynchronized access, it invokes the UnSyncUpdateResource method. 在每一組方法呼叫之後,應用程式執行緒會呼叫AutoResetEvent. WaitOne方法,使其封鎖, AutoResetEvent直到實例收到信號為止。After each set of method calls, the application thread calls the AutoResetEvent.WaitOne method so that it blocks until the AutoResetEvent instance is signaled.

每次呼叫 SyncUpdateResource 方法都會呼叫內部 SyncResource.Access 方法,然後呼叫 Interlocked.Decrement 方法以遞減 numOps 計數器。Each call to the SyncUpdateResource method calls the internal SyncResource.Access method and then calls the Interlocked.Decrement method to decrement the numOps counter. Interlocked.Decrement方法是用來遞減計數器,因為否則您無法確定第二個執行緒將會在第一個執行緒的遞減值儲存至變數之前存取值。The Interlocked.Decrement method Is used to decrement the counter, because otherwise you cannot be certain that a second thread will access the value before a first thread's decremented value has been stored in the variable. 當上次同步處理的背景工作執行緒將計數器遞減為零時,表示所有同步處理的執行緒都已完成SyncUpdateResource存取資源, EventWaitHandle.Set方法會呼叫方法,以通知主執行緒繼續進行。過程.When the last synchronized worker thread decrements the counter to zero, indicating that all synchronized threads have completed accessing the resource, the SyncUpdateResource method calls the EventWaitHandle.Set method, which signals the main thread to continue execution.

每次呼叫 UnSyncUpdateResource 方法都會呼叫內部 UnSyncResource.Access 方法,然後呼叫 Interlocked.Decrement 方法以遞減 numOps 計數器。Each call to the UnSyncUpdateResource method calls the internal UnSyncResource.Access method and then calls the Interlocked.Decrement method to decrement the numOps counter. 同樣地, Interlocked.Decrement方法是用來遞減計數器,以確保第二個執行緒在指派至變數之前,不會存取值。Once again, the Interlocked.Decrement method Is used to decrement the counter to ensure that a second thread does not access the value before a first thread's decremented value has been assigned to the variable. 當最後一個未同步處理的背景工作執行緒將計數器遞減為零,表示沒有更多未同步處理的執行緒UnSyncUpdateResource需要存取資源EventWaitHandle.Set時,方法會呼叫方法,以通知主執行緒繼續執行.When the last unsynchronized worker thread decrements the counter to zero, indicating that no more unsynchronized threads need to access the resource, the UnSyncUpdateResource method calls the EventWaitHandle.Set method, which signals the main thread to continue execution.

如範例輸出所示,同步存取可確保呼叫執行緒會先結束受保護的資源,其他執行緒才能存取該資源;每個執行緒都會等候其前置項。As the output from the example shows, synchronized access ensures that the calling thread exits the protected resource before another thread can access it; each thread waits on its predecessor. 相反地,若未鎖定,則會依執行緒到達的順序來呼叫 UnSyncResource.Access 方法。On the other hand, without the lock, the UnSyncResource.Access method is called in the order in which threads reach it.

備註

類別可讓您藉由Monitor.Enter呼叫、 Monitor.TryEnterMonitor.Exit方法,藉由取得和釋放特定物件的鎖定,來同步處理某個區域的程式碼存取。 MonitorThe Monitor class allows you to synchronize access to a region of code by taking and releasing a lock on a particular object by calling the Monitor.Enter, Monitor.TryEnter, and Monitor.Exit methods. 物件鎖定提供限制存取程式碼區塊的能力,通常稱為重要區段。Object locks provide the ability to restrict access to a block of code, commonly called a critical section. 當執行緒擁有物件的鎖定時,沒有其他執行緒可以取得該鎖定。While a thread owns the lock for an object, no other thread can acquire that lock. 您也可以使用Monitor類別來確保不允許其他任何執行緒存取鎖定擁有者所執行的應用程式代碼區段,除非另一個執行緒使用不同的鎖定物件來執行程式碼。You can also use the Monitor class to ensure that no other thread is allowed to access a section of application code being executed by the lock owner, unless the other thread is executing the code using a different locked object.

本文內容:In this article:

Monitor 類別:總覽 The Monitor class: An overview
Lock 物件 The lock object
重要區段 The critical section
脈衝、PulseAll 和 Wait Pulse, PulseAll, and Wait
監視器和等候控制碼Monitors and wait handles

Monitor 類別:總覽The Monitor class: An overview

Monitor具有下列功能:Monitor has the following features:

  • 它會隨選與物件相關聯。It is associated with an object on demand.

  • 它是未系結的,這表示可以從任何內容直接呼叫它。It is unbound, which means it can be called directly from any context.

  • 無法建立Monitor類別的實例; Monitor類別的方法都是靜態的。An instance of the Monitor class cannot be created; the methods of the Monitor class are all static. 會將控制存取關鍵區段的同步物件傳遞給每個方法。Each method is passed the synchronized object that controls access to the critical section.

注意

您可以Monitor使用類別來鎖定字串以外的物件(也就是以外的參考String型別),而不是實值型別。Use the Monitor class to lock objects other than strings (that is, reference types other than String), not value types. 如需詳細資訊,請參閱Enter這篇文章稍後的「方法」和「鎖定物件」一節。For details, see the overloads of the Enter method and The lock object section later in this article.

下表描述可供存取同步物件的執行緒所採取的動作:The following table describes the actions that can be taken by threads that access synchronized objects:

動作Action 說明Description
EnterTryEnterEnter, TryEnter 取得物件的鎖定。Acquires a lock for an object. 此動作也會標示重要區段的開頭。This action also marks the beginning of a critical section. 除非其他執行緒正在使用不同的鎖定物件來執行重要區段中的指示,否則無法進入重要區段。No other thread can enter the critical section unless it is executing the instructions in the critical section using a different locked object.
Wait 釋放物件的鎖定,以便允許其他執行緒鎖定和存取物件。Releases the lock on an object in order to permit other threads to lock and access the object. 呼叫執行緒會在另一個執行緒存取物件時等候。The calling thread waits while another thread accesses the object. 脈衝信號是用來通知等候中的執行緒有關物件狀態的變更。Pulse signals are used to notify waiting threads about changes to an object's state.
Pulse(信號)、PulseAllPulse (signal), PulseAll 將信號傳送給一或多個等候中的執行緒。Sends a signal to one or more waiting threads. 信號會通知等候中的執行緒,鎖定物件的狀態已變更,而且鎖定的擁有者已準備好釋放鎖定。The signal notifies a waiting thread that the state of the locked object has changed, and the owner of the lock is ready to release the lock. 等候中的執行緒會放在物件的就緒佇列中,因此它最後可能會收到物件的鎖定。The waiting thread is placed in the object's ready queue so that it might eventually receive the lock for the object. 一旦執行緒擁有鎖定,它就可以檢查物件的新狀態,以查看是否已達到所需的狀態。Once the thread has the lock, it can check the new state of the object to see if the required state has been reached.
Exit 釋放物件上的鎖定。Releases the lock on an object. 此動作也會標示受鎖定物件保護之重要區段的結尾。This action also marks the end of a critical section protected by the locked object.

從開始Enter TryEnter ,有兩組和方法的多載。 .NET Framework 4.NET Framework 4Beginning with the .NET Framework 4.NET Framework 4, there are two sets of overloads for the Enter and TryEnter methods. 一組多載具有ref (在中C#)或ByRef (在 Visual Basic) Boolean參數,如果取得鎖定,則會以自動方式設定為true ,即使取得鎖定時擲回例外狀況也一樣。One set of overloads has a ref (in C#) or ByRef (in Visual Basic) Boolean parameter that is atomically set to true if the lock is acquired, even if an exception is thrown when acquiring the lock. 如果在所有情況下都必須釋放鎖定,請使用這些多載,即使鎖定所保護的資源可能不是一致的狀態。Use these overloads if it is critical to release the lock in all cases, even when the resources the lock is protecting might not be in a consistent state.

Lock 物件The lock object

Monitor 類別是由static (在中C#)或Shared (在 Visual Basic)方法所組成,其會在控制重要區段存取的物件上運作。The Monitor class consists of static (in C#) or Shared (in Visual Basic) methods that operate on an object that controls access to the critical section. 會針對每個已同步處理的物件維護下列資訊:The following information is maintained for each synchronized object:

  • 目前持有鎖定之執行緒的參考。A reference to the thread that currently holds the lock.

  • 準備好的佇列的參考,其中包含準備好取得鎖定的執行緒。A reference to a ready queue, which contains the threads that are ready to obtain the lock.

  • 等待佇列的參考,其中包含正在等候鎖定物件狀態變更通知的往來文章。A reference to a waiting queue, which contains the threads that are waiting for notification of a change in the state of the locked object.

Monitor 會鎖定物件 (也就是參考類型),而不會鎖定值類型。Monitor locks objects (that is, reference types), not value types. 雖然您可以傳遞值類型到 EnterExit,它會個別針對每個呼叫進行 boxed 處理。While you can pass a value type to Enter and Exit, it is boxed separately for each call. 因為每個呼叫會建立不同的物件,Enter 絕不會封鎖,且它應該要保護的程式碼不會真地同步處理。Since each call creates a separate object, Enter never blocks, and the code it is supposedly protecting is not really synchronized. 此外,傳遞給 Exit 的物件不同於傳遞給 Enter 的物件,因此 Monitor 會擲回 SynchronizationLockException 例外狀況,以及訊息「從未同步處理的程式碼區塊呼叫物件同步化方法」。In addition, the object passed to Exit is different from the object passed to Enter, so Monitor throws SynchronizationLockException exception with the message "Object synchronization method was called from an unsynchronized block of code."

下列範例說明此問題。The following example illustrates this problem. 它會啟動 10 個工作,其中每個工作睡眠 250 毫秒。It launches ten tasks, each of which just sleeps for 250 milliseconds. 每一項工作接著會更新計數器變數 nTasks,這是要計算實際啟動並執行的工作數目。Each task then updates a counter variable, nTasks, which is intended to count the number of tasks that actually launched and executed. 由於 nTasks 是可以同時由多個工作更新的全域變數,因此使用監視器來防止多個工作同時修改。Because nTasks is a global variable that can be updated by multiple tasks simultaneously, a monitor is used to protect it from simultaneous modification by multiple tasks. 不過,如範例的輸出所示,每項工作都擲回 SynchronizationLockException 例外狀況。However, as the output from the example shows, each of the tasks throws a SynchronizationLockException exception.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {

      int nTasks = 0;
      List<Task> tasks = new List<Task>();
      
      try {
         for (int ctr = 0; ctr < 10; ctr++)
            tasks.Add(Task.Run( () => { // Instead of doing some work, just sleep.
                                        Thread.Sleep(250);
                                        // Increment the number of tasks.
                                        Monitor.Enter(nTasks);
                                        try {
                                           nTasks += 1;
                                        }
                                        finally {
                                           Monitor.Exit(nTasks);
                                        }
                                      } ));
         Task.WaitAll(tasks.ToArray());
         Console.WriteLine("{0} tasks started and executed.", nTasks);
      }
      catch (AggregateException e) {
         String msg = String.Empty;
         foreach (var ie in e.InnerExceptions) {
            Console.WriteLine("{0}", ie.GetType().Name);
            if (! msg.Contains(ie.Message))
               msg += ie.Message + Environment.NewLine;
         }
         Console.WriteLine("\nException Message(s):");
         Console.WriteLine(msg);
      }
   }
}
// The example displays the following output:
//    SynchronizationLockException
//    SynchronizationLockException
//    SynchronizationLockException
//    SynchronizationLockException
//    SynchronizationLockException
//    SynchronizationLockException
//    SynchronizationLockException
//    SynchronizationLockException
//    SynchronizationLockException
//    SynchronizationLockException
//
//    Exception Message(s):
//    Object synchronization method was called from an unsynchronized block of code.
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim nTasks As Integer = 0
      Dim tasks As New List(Of Task)()

      Try
         For ctr As Integer = 0 To 9
            tasks.Add(Task.Run( Sub()
                                   ' Instead of doing some work, just sleep.
                                   Thread.Sleep(250)
                                   ' Increment the number of tasks.
                                   Monitor.Enter(nTasks)
                                   Try
                                      nTasks += 1
                                   Finally
                                      Monitor.Exit(nTasks)
                                   End Try
                                End Sub))
         Next
         Task.WaitAll(tasks.ToArray())
         Console.WriteLine("{0} tasks started and executed.", nTasks)
      Catch e As AggregateException
         Dim msg AS String = String.Empty
         For Each ie In e.InnerExceptions
            Console.WriteLine("{0}", ie.GetType().Name)
            If Not msg.Contains(ie.Message) Then
               msg += ie.Message + Environment.NewLine
            End If
         Next
         Console.WriteLine(vbCrLf + "Exception Message(s):")
         Console.WriteLine(msg)
      End Try
   End Sub
End Module
' The example displays the following output:
'    SynchronizationLockException
'    SynchronizationLockException
'    SynchronizationLockException
'    SynchronizationLockException
'    SynchronizationLockException
'    SynchronizationLockException
'    SynchronizationLockException
'    SynchronizationLockException
'    SynchronizationLockException
'    SynchronizationLockException
'
'    Exception Message(s):
'    Object synchronization method was called from an unsynchronized block of code.

每個工作都擲回 SynchronizationLockException 例外狀況是因為 nTasks 變數在呼叫每個工作中的 Monitor.Enter 方法之前會進行 boxed 處理。Each task throws a SynchronizationLockException exception because the nTasks variable is boxed before the call to the Monitor.Enter method in each task. 換句話說,每個方法呼叫都被傳遞個別的變數,且與其他變數無關。In other words, each method call is passed a separate variable that is independent of the others. nTasks 在呼叫 Monitor.Exit 方法時會再次進行 boxed 處理。nTasks is boxed again in the call to the Monitor.Exit method. 同樣地,這會建立十個彼此獨立的新 boxed 變數 nTasks,以及在呼叫 Monitor.Enter 方法時建立的十個 boxed 變數。Once again, this creates ten new boxed variables, which are independent of each other, nTasks, and the ten boxed variables created in the call to the Monitor.Enter method. 接著便擲回例外狀況,因為我們的程式碼嘗試對於先前未鎖定的新建變數釋放鎖定。The exception is thrown, then, because our code is attempting to release a lock on a newly created variable that was not previously locked.

雖然您可以先將值類型變數進行 box 處理,然後再呼叫 EnterExit,如下列範例所示,並將相同的 boxed 物件傳遞給這兩種方法,但這麼做並沒有任何益處。Although you can box a value type variable before calling Enter and Exit, as shown in the following example, and pass the same boxed object to both methods, there is no advantage to doing this. 變更 unboxed 變數不會反映在 boxed 複本,且沒有任何方法可變更 boxed 複本的值。Changes to the unboxed variable are not reflected in the boxed copy, and there is no way to change the value of the boxed copy.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {

      int nTasks = 0;
      object o = nTasks;
      List<Task> tasks = new List<Task>();
      
      try {
         for (int ctr = 0; ctr < 10; ctr++)
            tasks.Add(Task.Run( () => { // Instead of doing some work, just sleep.
                                        Thread.Sleep(250);
                                        // Increment the number of tasks.
                                        Monitor.Enter(o);
                                        try {
                                           nTasks++;
                                        }
                                        finally {
                                           Monitor.Exit(o);
                                        }
                                      } ));
         Task.WaitAll(tasks.ToArray());
         Console.WriteLine("{0} tasks started and executed.", nTasks);
      }
      catch (AggregateException e) {
         String msg = String.Empty;
         foreach (var ie in e.InnerExceptions) {
            Console.WriteLine("{0}", ie.GetType().Name);
            if (! msg.Contains(ie.Message))
               msg += ie.Message + Environment.NewLine;
         }
         Console.WriteLine("\nException Message(s):");
         Console.WriteLine(msg);
      }
   }
}
// The example displays the following output:
//        10 tasks started and executed.
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim nTasks As Integer = 0
      Dim o As Object = nTasks
      Dim tasks As New List(Of Task)()

      Try
         For ctr As Integer = 0 To 9
            tasks.Add(Task.Run( Sub()
                                   ' Instead of doing some work, just sleep.
                                   Thread.Sleep(250)
                                   ' Increment the number of tasks.
                                   Monitor.Enter(o)
                                   Try
                                      nTasks += 1
                                   Finally
                                      Monitor.Exit(o)
                                   End Try
                                End Sub))
         Next
         Task.WaitAll(tasks.ToArray())
         Console.WriteLine("{0} tasks started and executed.", nTasks)
      Catch e As AggregateException
         Dim msg AS String = String.Empty
         For Each ie In e.InnerExceptions
            Console.WriteLine("{0}", ie.GetType().Name)
            If Not msg.Contains(ie.Message) Then
               msg += ie.Message + Environment.NewLine
            End If
         Next
         Console.WriteLine(vbCrLf + "Exception Message(s):")
         Console.WriteLine(msg)
      End Try
   End Sub
End Module
' The example displays the following output:
'       10 tasks started and executed.

選取要同步處理的物件時,您應該只鎖定私用或內建物件。When selecting an object on which to synchronize, you should lock only on private or internal objects. 對外部物件的鎖定可能會導致鎖死,因為不相關的程式碼可以針對不同的目的,選擇鎖定相同的物件。Locking on external objects might result in deadlocks, because unrelated code could choose the same objects to lock on for different purposes.

請注意,如果用於鎖定的物件衍生MarshalByRefObject自,您可以在多個應用程式域中的物件上進行同步處理。Note that you can synchronize on an object in multiple application domains if the object used for the lock derives from MarshalByRefObject.

重要區段The critical section

Enter使用和Exit方法來標記重要區段的開頭和結尾。Use the Enter and Exit methods to mark the beginning and end of a critical section.

注意

Enter C# 和方法Exit所提供的功能與中 lock 語句所提供的功能相同,而且 Visual Basic 中的SyncLock語句,不同之處在于語言結構會包裝Monitor.Enter(Object, Boolean)方法多載和Monitor.Exittry的方法 .。。finallyThe functionality provided by the Enter and Exit methods is identical to that provided by the lock statement in C# and the SyncLock statement in Visual Basic, except that the language constructs wrap the Monitor.Enter(Object, Boolean) method overload and the Monitor.Exit method in a tryfinally [封鎖] 以確保已釋放監視器。block to ensure that the monitor is released.

如果重要區段是一組連續的指示,則Enter方法所取得的鎖定會保證只有一個執行緒可以使用鎖定的物件來執行包含的程式碼。If the critical section is a set of contiguous instructions, then the lock acquired by the Enter method guarantees that only a single thread can execute the enclosed code with the locked object. 在此情況下,建議您將該程式碼放在try區塊中,並將該Exit方法的呼叫放finally在區塊中。In this case, we recommend that you place that code in a try block and place the call to the Exit method in a finally block. 這可確保即使發生例外狀況,就會釋放鎖定。This ensures that the lock is released even if an exception occurs. 下列程式碼片段說明此模式。The following code fragment illustrates this pattern.

// Define the lock object.
var obj = new Object();

// Define the critical section.
Monitor.Enter(obj);
try {
   // Code to execute one thread at a time.
}
// catch blocks go here.
finally {
   Monitor.Exit(obj);
}
' Define the lock object.
Dim obj As New Object()

' Define the critical section.
Monitor.Enter(obj)
Try 
   ' Code to execute one thread at a time.

' catch blocks go here.
Finally 
   Monitor.Exit(obj)
End Try

這項功能通常用來同步處理對類別之靜態或實例方法的存取。This facility is typically used to synchronize access to a static or instance method of a class.

如果重要區段跨越整個方法,則可以將放System.Runtime.CompilerServices.MethodImplAttribute在方法上,並在的程式中Synchronized指定System.Runtime.CompilerServices.MethodImplAttribute值,藉以達成鎖定設備。If a critical section spans an entire method, the locking facility can be achieved by placing the System.Runtime.CompilerServices.MethodImplAttribute on the method, and specifying the Synchronized value in the constructor of System.Runtime.CompilerServices.MethodImplAttribute. 當您使用這個屬性時, EnterExit需要和方法呼叫。When you use this attribute, the Enter and Exit method calls are not needed. 下列程式碼片段說明此模式:The following code fragment illustrates this pattern:

[MethodImplAttribute(MethodImplOptions.Synchronized)]
void MethodToLock()
{
   // Method implementation.
} 
<MethodImplAttribute(MethodImplOptions.Synchronized)>
Sub MethodToLock()
   ' Method implementation.
End Sub 

請注意,屬性會使目前的執行緒保留鎖定,直到方法傳回為止。如果可以更快釋放鎖定,請使用Monitor類別、 C# lock 語句或方法內的 Visual Basic SyncLock語句,而不是屬性。Note that the attribute causes the current thread to hold the lock until the method returns; if the lock can be released sooner, use the Monitor class, the C# lock statement, or the Visual Basic SyncLock statement inside of the method instead of the attribute.

雖然EnterExit語句可能會鎖定和釋放指定物件以跨越成員或類別界限或兩者,但不建議這樣做。While it is possible for the Enter and Exit statements that lock and release a given object to cross member or class boundaries or both, this practice is not recommended.

脈衝、PulseAll 和 WaitPulse, PulseAll, and Wait

一旦執行緒擁有鎖定,並已進入鎖定所保護的重要區段,它就可以呼叫Monitor.WaitMonitor.PulseMonitor.PulseAll方法。Once a thread owns the lock and has entered the critical section that the lock protects, it can call the Monitor.Wait, Monitor.Pulse, and Monitor.PulseAll methods.

持有鎖定的執行緒呼叫Wait時,會釋放鎖定,並將執行緒加入至已同步處理物件的等候佇列中。When the thread that holds the lock calls Wait, the lock is released and the thread is added to the waiting queue of the synchronized object. 就緒佇列中的第一個執行緒(如果有的話)會取得鎖定並進入重要區段。The first thread in the ready queue, if any, acquires the lock and enters the critical section. Wait Monitor.Pulse或方法Monitor.PulseAll是由持有鎖定的執行緒所呼叫時,呼叫的執行緒會從等候佇列移到就緒佇列(要移動的執行緒必須在等候佇列的開頭)。The thread that called Wait is moved from the waiting queue to the ready queue when either the Monitor.Pulse or the Monitor.PulseAll method is called by the thread that holds the lock (to be moved, the thread must be at the head of the waiting queue). 呼叫Wait執行緒重新取得鎖定時,方法會傳回。The Wait method returns when the calling thread reacquires the lock.

當持有鎖定的執行緒呼叫Pulse時,等待佇列開頭的執行緒會移到就緒佇列。When the thread that holds the lock calls Pulse, the thread at the head of the waiting queue is moved to the ready queue. PulseAll方法的呼叫會將等候佇列中的所有線程移至就緒佇列。The call to the PulseAll method moves all the threads from the waiting queue to the ready queue.

監視器和等候控制碼Monitors and wait handles

請務必注意,使用Monitor類別和WaitHandle物件之間的區別。It is important to note the distinction between the use of the Monitor class and WaitHandle objects.

  • Monitor類別純粹是受控、完全可攜,而且可能在作業系統資源需求方面更有效率。The Monitor class is purely managed, fully portable, and might be more efficient in terms of operating-system resource requirements.

  • WaitHandle 物件代表作業系統可等候物件、適用於 managed 和 unmanaged 程式碼之間的同步處理,並且公開一些進階的作業系統功能,例如一次等候許多物件的能力。WaitHandle objects represent operating-system waitable objects, are useful for synchronizing between managed and unmanaged code, and expose some advanced operating-system features like the ability to wait on many objects at once.

屬性

LockContentionCount

取得嘗試取得監視器鎖定時發生的競爭次數。Gets the number of times there was contention when trying to take the monitor's lock.

方法

Enter(Object)

取得指定物件的獨佔鎖定。Acquires an exclusive lock on the specified object.

Enter(Object, Boolean)

取得指定之物件的獨佔鎖定,並且完整設定值,指出是否採用鎖定。Acquires an exclusive lock on the specified object, and atomically sets a value that indicates whether the lock was taken.

Exit(Object)

釋出指定物件的獨佔鎖定。Releases an exclusive lock on the specified object.

IsEntered(Object)

判斷目前執行緒是否保持鎖定指定的物件。Determines whether the current thread holds the lock on the specified object.

Pulse(Object)

通知等候佇列中的執行緒,鎖定物件的狀態有所變更。Notifies a thread in the waiting queue of a change in the locked object's state.

PulseAll(Object)

通知所有等候中的執行緒,物件的狀態有所變更。Notifies all waiting threads of a change in the object's state.

TryEnter(Object)

嘗試取得指定物件的獨佔鎖定。Attempts 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, Int32)

嘗試取得指定物件的獨佔鎖定 (在指定的毫秒數時間內)。Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object.

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

Wait(Object)

釋出物件的鎖並且封鎖目前的執行緒,直到這個執行緒重新取得鎖定為止。Releases the lock on an object and blocks the current thread until it reacquires the lock.

Wait(Object, Int32)

釋出物件的鎖並且封鎖目前的執行緒,直到這個執行緒重新取得鎖定為止。Releases the lock on an object and blocks the current thread until it reacquires the lock. 如果超過指定的逾時間隔時間,執行緒會進入就緒序列。If the specified time-out interval elapses, the thread enters the ready queue.

Wait(Object, Int32, Boolean)

釋出物件的鎖並且封鎖目前的執行緒,直到這個執行緒重新取得鎖定為止。Releases the lock on an object and blocks the current thread until it reacquires the lock. 如果超過指定的逾時間隔時間,執行緒會進入就緒序列。If the specified time-out interval elapses, the thread enters the ready queue. 這個方法也會指定等候之前和重新取得之後,是否要離開內容 (Context) 的同步處理領域 (如果在同步化內容中的話)。This method also specifies whether the synchronization domain for the context (if in a synchronized context) is exited before the wait and reacquired afterward.

Wait(Object, TimeSpan)

釋出物件的鎖並且封鎖目前的執行緒,直到這個執行緒重新取得鎖定為止。Releases the lock on an object and blocks the current thread until it reacquires the lock. 如果超過指定的逾時間隔時間,執行緒會進入就緒序列。If the specified time-out interval elapses, the thread enters the ready queue.

Wait(Object, TimeSpan, Boolean)

釋出物件的鎖並且封鎖目前的執行緒,直到這個執行緒重新取得鎖定為止。Releases the lock on an object and blocks the current thread until it reacquires the lock. 如果超過指定的逾時間隔時間,執行緒會進入就緒序列。If the specified time-out interval elapses, the thread enters the ready queue. 在等候之前和重新取得領域之後,可選擇性地結束同步化內容的同步處理領域。Optionally exits the synchronization domain for the synchronized context before the wait and reacquires the domain afterward.

適用於

執行緒安全性

此型別具備執行緒安全。This type is thread safe.

另請參閱