监视器
更新: 2008 年 7 月
Monitor 对象通过使用 Monitor.Enter、Monitor.TryEnter 和 Monitor.Exit 方法对特定对象获取锁和释放锁来公开同步访问代码区域的能力。在对代码区域获取锁后,就可以使用 Monitor.Wait、Monitor.Pulse 和 Monitor.PulseAll 方法了。如果锁被暂挂,则 Wait 释放该锁并等待通知。当 Wait 接到通知后,它将返回并再次获取该锁。Pulse 和 PulseAll 都会发出信号以便等待队列中的下一个线程继续执行。
Visual Basic SyncLock 和 C# lock 语句使用 Monitor.Enter 获取锁,使用 Monitor.Exit 释放锁。使用语言语句的优点在于 lock 或 SyncLock 块中的所有内容都包含在 Try 语句中。Try 语句有一个 Finally 块,用以保证锁得以释放。
Monitor 将锁定对象(即引用类型),而非值类型。尽管可以向 Enter 和 Exit 传递值类型,但对于每次调用它都是分别装箱的。因为每次调用都创建一个独立的对象,所以 Enter 永远不会阻止,而且它要保护的代码并没有真正同步。另外,传递给 Exit 的对象不同于传递给 Enter 的对象,所以 Monitor 引发 SynchronizationLockException,并显示以下消息:“从不同步的代码块中调用了对象同步方法”。下面的示例演示这些问题。
Private x As Integer
' The next line creates a generic object containing the value of
' x each time the code is executed, so that Enter never blocks.
Monitor.Enter(x)
Try
' Code that needs to be protected by the monitor.
Finally
' Always use Finally to ensure that you exit the Monitor.
' The following line creates another object containing
' the value of x, and throws SynchronizationLockException
' because the two objects do not match.
Monitor.Exit(x)
End Try
private int x;
// The next line creates a generic object containing the value of
// x each time the code is executed, so that Enter never blocks.
Monitor.Enter(x);
try {
// Code that needs to be protected by the monitor.
}
finally {
// Always use Finally to ensure that you exit the Monitor.
// The following line creates another object containing
// the value of x, and throws SynchronizationLockException
// because the two objects do not match.
Monitor.Exit(x);
}
尽管您可以如下面的示例所示,在调用 Enter 和 Exit 之前将值类型变量装箱,并将同一个装箱的对象传递给这两个方法,但这样做并没有什么特别的用处。对变量的更改不能在装箱的变量中体现出来,也没有办法更改已装箱的变量的值。
Private o As Object = x
private Object o = x;
注意到 Monitor 和 WaitHandle 对象在使用上的区别是非常重要的。Monitor 对象是完全托管、完全可移植的,并且在操作系统资源要求方面可能更为有效。WaitHandle 对象表示操作系统可等待对象,对于在托管和非托管代码之间进行同步非常有用,并公开一些高级操作系统功能(如同时等待许多对象的能力)。
下面的代码示例演示 Monitor 类(使用 lock 和 SyncLock 编译器语句实现)、Interlocked 类和 AutoResetEvent 类的结合使用。
Imports System
Imports System.Threading
Imports Microsoft.VisualBasic
' Note: The class whose internal public member is the synchronizing method
' is not public; none of the client code takes a lock on the Resource object.
' The member of the nonpublic class takes the lock on itself. Written this
' way, malicious code cannot take a lock on a public object.
Class SyncResource
Public Sub Access(threadNum As Int32)
' Uses Monitor class to enforce synchronization.
SyncLock Me
' Synchronized: Despite the next conditional, each thread
' waits on its predecessor.
If threadNum Mod 2 = 0 Then
Thread.Sleep(2000)
End If
Console.WriteLine("Start Synched Resource access (Thread={0})", threadNum)
Thread.Sleep(200)
Console.WriteLine("Stop Synched Resource access (Thread={0})", threadNum)
End SyncLock
End Sub 'Access
End Class 'SyncResource
' Without the lock, the method is called in the order in which
' threads reach it.
Class UnSyncResource
Public Sub Access(threadNum As Int32)
' Does not use Monitor class to enforce synchronization.
' The next call throws the thread order.
If threadNum Mod 2 = 0 Then
Thread.Sleep(2000)
End If
Console.WriteLine("Start UnSynched Resource access (Thread={0})", threadNum)
Thread.Sleep(200)
Console.WriteLine("Stop UnSynched Resource access (Thread={0})", threadNum)
End Sub 'Access
End Class 'UnSyncResource
Public Class App
Private Shared numAsyncOps As Int32 = 5
Private Shared asyncOpsAreDone As New AutoResetEvent(False)
Private Shared SyncRes As New SyncResource()
Private Shared UnSyncRes As New UnSyncResource()
Private Shared threadNum As Int32
Public Shared Sub Main()
For threadNum = 0 To 4
ThreadPool.QueueUserWorkItem(AddressOf SyncUpdateResource, threadNum)
Next threadNum
' Wait until this WaitHandle is signaled.
asyncOpsAreDone.WaitOne()
Console.WriteLine(ControlChars.Tab + ControlChars.Lf + "All synchronized operations have completed." + ControlChars.Lf)
' Reset the thread count for unsynchronized calls.
numAsyncOps = 5
For threadNum = 0 To 4
ThreadPool.QueueUserWorkItem(AddressOf UnSyncUpdateResource, threadNum)
Next threadNum
' Wait until this WaitHandle is signaled.
asyncOpsAreDone.WaitOne()
Console.WriteLine(ControlChars.Tab + ControlChars.Cr + "All unsynchronized thread operations have completed.")
End Sub 'Main
' The callback method's signature MUST match that of
' a System.Threading.TimerCallback delegate
' (it takes an Object parameter and returns void).
Shared Sub SyncUpdateResource(state As Object)
' This calls the internal synchronized method, passing
' a thread number.
SyncRes.Access(CType(state, Int32))
' Count down the number of methods that the threads have called.
' This must be synchronized, however; you cannot know which thread
' will access the value **before** another thread's incremented
' value has been stored into the variable.
If Interlocked.Decrement(numAsyncOps) = 0 Then
asyncOpsAreDone.Set()
' Announce to Main that in fact all thread calls are done.
End If
End Sub 'SyncUpdateResource
' The callback method's signature MUST match that of
' a System.Threading.TimerCallback delegate
' (it takes an Object parameter and returns void).
Shared Sub UnSyncUpdateResource(state As [Object])
' This calls the unsynchronized method, passing
' a thread number.
UnSyncRes.Access(CType(state, Int32))
' Count down the number of methods that the threads have called.
' This must be synchronized, however; you cannot know which thread
' will access the value **before** another thread's incremented
' value has been stored into the variable.
If Interlocked.Decrement(numAsyncOps) = 0 Then
asyncOpsAreDone.Set()
' Announce to Main that in fact all thread calls are done.
End If
End Sub 'UnSyncUpdateResource
End Class 'App
using System;
using System.Threading;
// Note: The class whose internal public member is the synchronizing
// method is not public; none of the client code takes a lock on the
// Resource object.The member of the nonpublic class takes the lock on
// itself. Written this way, malicious code cannot take a lock on
// a public object.
class SyncResource {
public void Access(Int32 threadNum) {
// Uses Monitor class to enforce synchronization.
lock (this) {
// Synchronized: Despite the next conditional, each thread
// waits on its predecessor.
if (threadNum % 2 == 0)
Thread.Sleep(2000);
Console.WriteLine("Start Synched Resource access (Thread={0})", threadNum);
Thread.Sleep(200);
Console.WriteLine("Stop Synched Resource access (Thread={0})", threadNum);
}
}
}
// Without the lock, the method is called in the order in which threads reach it.
class UnSyncResource {
public void Access(Int32 threadNum) {
// Does not use Monitor class to enforce synchronization.
// The next call throws the thread order.
if (threadNum % 2 == 0)
Thread.Sleep(2000);
Console.WriteLine("Start UnSynched Resource access (Thread={0})", threadNum);
Thread.Sleep(200);
Console.WriteLine("Stop UnSynched Resource access (Thread={0})", threadNum);
}
}
public class App {
static Int32 numAsyncOps = 5;
static AutoResetEvent asyncOpsAreDone = new AutoResetEvent(false);
static SyncResource SyncRes = new SyncResource();
static UnSyncResource UnSyncRes = new UnSyncResource();
public static void Main() {
for (Int32 threadNum = 0; threadNum < 5; threadNum++) {
ThreadPool.QueueUserWorkItem(new WaitCallback(SyncUpdateResource), threadNum);
}
// Wait until this WaitHandle is signaled.
asyncOpsAreDone.WaitOne();
Console.WriteLine("\t\nAll synchronized operations have completed.\t\n");
// Reset the thread count for unsynchronized calls.
numAsyncOps = 5;
for (Int32 threadNum = 0; threadNum < 5; threadNum++) {
ThreadPool.QueueUserWorkItem(new WaitCallback(UnSyncUpdateResource), threadNum);
}
// Wait until this WaitHandle is signaled.
asyncOpsAreDone.WaitOne();
Console.WriteLine("\t\nAll unsynchronized thread operations have completed.");
}
// The callback method's signature MUST match that of a
// System.Threading.TimerCallback delegate (it takes an Object
// parameter and returns void).
static void SyncUpdateResource(Object state) {
// This calls the internal synchronized method, passing
// a thread number.
SyncRes.Access((Int32) state);
// Count down the number of methods that the threads have called.
// This must be synchronized, however; you cannot know which thread
// will access the value **before** another thread's incremented
// value has been stored into the variable.
if (Interlocked.Decrement(ref numAsyncOps) == 0)
asyncOpsAreDone.Set();
// Announce to Main that in fact all thread calls are done.
}
// The callback method's signature MUST match that of a
// System.Threading.TimerCallback delegate (it takes an Object
// parameter and returns void).
static void UnSyncUpdateResource(Object state) {
// This calls the unsynchronized method, passing a thread number.
UnSyncRes.Access((Int32) state);
// Count down the number of methods that the threads have called.
// This must be synchronized, however; you cannot know which thread
// will access the value **before** another thread's incremented
// value has been stored into the variable.
if (Interlocked.Decrement(ref numAsyncOps) == 0)
asyncOpsAreDone.Set();
// Announce to Main that in fact all thread calls are done.
}
}
请参见
参考
其他资源
修订记录
日期 |
修订记录 |
原因 |
---|---|---|
2008 年 7 月 |
新增阐述:SyncLock 和 lock 语句使用 Monitor.Enter 和 Exit。 |
客户反馈。 |