在C#中,Wait和Lock可以一起使用,但它們分別屬于不同的類:Wait屬于System.Threading.Monitor類,而Lock屬于System.Threading.Monitor類的一個靜態屬性。
Monitor.Wait方法用于等待一個對象監視器上的鎖被釋放。當調用Monitor.Wait方法時,當前線程會釋放對象的鎖并進入等待狀態。當其他線程調用Monitor.Pulse或Monitor.PulseAll方法時,等待的線程將被喚醒并重新嘗試獲取對象的鎖。
Monitor.Lock是一個靜態屬性,用于獲取一個對象的監視器上的鎖。當調用Monitor.Lock方法時,當前線程會獲取對象的鎖并繼續執行。如果鎖已被其他線程持有,則當前線程將阻塞,直到鎖被釋放。
以下是一個使用Monitor.Wait和Monitor.Lock的示例:
using System;
using System.Threading;
class Program
{
private static readonly object _lockObject = new object();
static void Main()
{
Thread thread1 = new Thread(Thread1);
Thread thread2 = new Thread(Thread2);
thread1.Start();
thread2.Start();
}
static void Thread1()
{
Monitor.Lock(_lockObject);
Console.WriteLine("Thread1 acquired the lock.");
// Simulate some work
Thread.Sleep(1000);
Monitor.Wait(_lockObject);
Console.WriteLine("Thread1 released the lock and is waiting.");
// Simulate some more work
Thread.Sleep(1000);
Monitor.Exit(_lockObject);
Console.WriteLine("Thread1 exited.");
}
static void Thread2()
{
Monitor.Lock(_lockObject);
Console.WriteLine("Thread2 acquired the lock.");
// Simulate some work
Thread.Sleep(1000);
Monitor.Pulse(_lockObject);
Console.WriteLine("Thread2 pulsed the lock.");
Monitor.Exit(_lockObject);
Console.WriteLine("Thread2 exited.");
}
}
在這個示例中,Thread1和Thread2都嘗試獲取同一個對象的鎖。Thread1首先獲取鎖并執行一些工作,然后釋放鎖并等待。Thread2在Thread1釋放鎖后獲取鎖并執行一些工作,然后通過Monitor.Pulse喚醒Thread1。最后,兩個線程都釋放鎖并退出。