地球人都知道,使用lock關鍵字可以獲取一個對象的獨占權,任何需要獲取這個對象的操作的線程必須等待以獲取該對象的線程釋放獨占權,lock提供了簡單的同步資源的方法,與Java中的synchronized關鍵字類似。
lock關鍵字的使用示例代碼如下
object o = new object();
lock (o)
{
Console.WriteLine("O");
}
4.使用System.Theading.Monitor類進行同步
system.Threading.Monitor類提供了與lock類似的功能,不過與lock不同的是,它能更好的控制同步塊,當調用了Monitor的Enter(Object o)方法時,會獲取o的獨占權,直到調用Exit(Object o)方法時,才會釋放對o的獨占權,可以多次調用Enter(Object o)方法,只需要調用同樣次數的Exit(Object o)方法即可,Monitor類同時提供了TryEnter(Object o,[int])的一個重載方法,該方法嘗試獲取o對象的獨占權,當獲取獨占權失敗時,將返回false,查看如下代碼
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace MonitorApplication
{
class Program
{
private static object m_monitorObject = new object();
static void Main(string[] args)
{
Thread thread = new Thread(Do);
thread.Name = "Thread1";
Thread thread2 = new Thread(Do);
thread2.Name = "Thread2";
thread.Start();
thread2.Start();
thread.Join();
thread2.Join();
}
static void Do()
{
if (!Monitor.TryEnter(m_monitorObject))
{
Console.WriteLine("Can't visit Object " + Thread.CurrentThread.Name);
return;
}
try
{
Monitor.Enter(m_monitorObject);
Console.WriteLine("Enter Monitor " + Thread.CurrentThread.Name);
Thread.Sleep(5000);
}
finally
{
Monitor.Exit(m_monitorObject);
}
}
}
}