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,并显示消息“从不同步的代码块中调用了对象同步方法”。下面的示例演示这些问题。
Try
Dim x As Integer = 1
' The call to Enter() creates a generic synchronizing object for 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 call to Exit() will FAIL!!!
' The synchronizing object created for x in Exit() will be different
' than the object used in Enter(). SynchronizationLockException
' will be thrown.
Monitor.Exit(x)
End Try
Catch SyncEx As SynchronizationLockException
Console.WriteLine("A SynchronizationLockException occurred. Message:")
Console.WriteLine(SyncEx.Message)
End Try
try
{
int x = 1;
// The call to Enter() creates a generic synchronizing object for 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 call to Exit() will FAIL!!!
// The synchronizing object created for x in Exit() will be different
// than the object used in Enter(). SynchronizationLockException
// will be thrown.
Monitor.Exit(x);
}
}
catch (SynchronizationLockException SyncEx)
{
Console.WriteLine("A SynchronizationLockException occurred. Message:");
Console.WriteLine(SyncEx.Message);
}
try
{
int x = 1;
// The call to Enter() creates a generic synchronizing object for 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 call to Exit() will FAIL!!!
// The synchronizing object created for x in Exit() will be different
// than the object used in Enter(). SynchronizationLockException
// will be thrown.
Monitor::Exit(x);
}
}
catch (SynchronizationLockException^ SyncEx)
{
Console::WriteLine("A SynchronizationLockException occurred. Message:");
Console::WriteLine(SyncEx->Message);
}
虽然您可以在调用 Enter 和 Exit 之前装箱值类型变量(如下面的示例所示),并将相同的装箱对象同时传递给两个方法,但是这样做没有任何好处。 对变量的更改不能在装箱的变量中体现出来,也没有办法更改已装箱的变量的值。
Dim x As Integer = 1
Dim o As object = x
Monitor.Enter(o)
Try
' Code that needs to be protected by the monitor.
Finally
' Always use Finally to ensure that you exit the Monitor.
Monitor.Exit(o)
End Try
int x = 1;
object o = x;
Monitor.Enter(o);
try
{
// Code that needs to be protected by the monitor.
}
finally
{
// Always use Finally to ensure that you exit the Monitor.
Monitor.Exit(o);
}
int x = 1;
Object^ o = x;
Monitor::Enter(o);
try
{
// Code that needs to be protected by the monitor.
}
finally
{
// Always use Finally to ensure that you exit the Monitor.
Monitor::Exit(o);
}
请务必注意 Monitor 对象和 WaitHandle 对象在使用上的区别。 Monitor 对象是纯托管的,并且完全可移植,从操作系统资源要求来看可能更为高效。 WaitHandle 对象表示操作系统可等待的对象,对于在托管和非托管代码之间实现同步非常有用,并提供一些高级的操作系统功能,例如同时等待多个对象的功能。
下面的代码示例演示 Monitor 类(使用 lock 和 SyncLock 编译器语句实现)、Interlocked 类和 AutoResetEvent 类的结合使用。
Imports System
Imports 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 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
End Class
' 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
End Class
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()
Public Shared Sub Main()
For threadNum As Int32 = 0 To 4
ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf SyncUpdateResource), threadNum)
Next threadNum
' Wait until this WaitHandle is signaled.
asyncOpsAreDone.WaitOne()
Console.WriteLine(vbTab + vbNewLine + "All synchronized operations have completed." + vbTab + vbNewLine)
' Reset the thread count for unsynchronized calls.
numAsyncOps = 5
For threadNum As Int32 = 0 To 4
ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf UnSyncUpdateResource), threadNum)
Next threadNum
' Wait until this WaitHandle is signaled.
asyncOpsAreDone.WaitOne()
Console.WriteLine("\t\nAll unsynchronized thread operations have completed.")
End Sub
' 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
' Announce to Main that in fact all thread calls are done.
asyncOpsAreDone.Set()
End If
End Sub
' 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
' Announce to Main that in fact all thread calls are done.
asyncOpsAreDone.Set()
End If
End Sub
End Class
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)
{
// Announce to Main that in fact all thread calls are done.
asyncOpsAreDone.Set();
}
}
// 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)
{
// Announce to Main that in fact all thread calls are done.
asyncOpsAreDone.Set();
}
}
}
#using <System.dll>
using namespace System;
using namespace 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.
ref class SyncResource
{
public:
void Access(Int32 threadNum)
{
// Uses Monitor class to enforce synchronization.
Monitor::Enter(this);
try
{
// 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);
}
finally
{
Monitor::Exit(this);
}
}
};
// Without the lock, the method is called in the order in which threads reach it.
ref 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 ref class App
{
private:
static Int32 numAsyncOps = 5;
static AutoResetEvent^ asyncOpsAreDone = gcnew AutoResetEvent(false);
static SyncResource^ SyncRes = gcnew SyncResource();
static UnSyncResource^ UnSyncRes = gcnew UnSyncResource();
public:
static void Main()
{
for (Int32 threadNum = 0; threadNum < 5; threadNum++)
{
ThreadPool::QueueUserWorkItem(gcnew 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(gcnew 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(numAsyncOps) == 0)
{
// Announce to Main that in fact all thread calls are done.
asyncOpsAreDone->Set();
}
}
// 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(numAsyncOps) == 0)
{
// Announce to Main that in fact all thread calls are done.
asyncOpsAreDone->Set();
}
}
};
int main()
{
App::Main();
}