日期:2014-05-19  浏览次数:20917 次

求教:请问纯粹使用lock,和调用moniter.pulse有什么区别?
例如
两个线程同时调用如下代码

lock(object)
{
}



lock(object)
{
      Monitor.PulseAll();
}

有什么区别呢?

------解决方案--------------------
Monitor.PulseAll() 通常和Monitor.Wait() 配合使用; 当一个线程运行了Monitor.Wait() 就会阻塞在这个语句上,一直到有另外一个线程运行Monitor.PulseAll()才能得到没锁Object的锁,并且继续运行.

它们二者配合使用是线程之间传递共享资源的状态变化的.

下边有个例子:

private ArrayList arrayList = new ArrayList();


public void Method1() // Thread-safe method.
{
lock (arrayList)
{
// Imagine we need at least two items.
while (arrayList.Count < 2)
Monitor.Wait(arrayList);


// Do work with the items…
}


}


public void AddItem(object item) // Thread-safe method.
{
lock (arrayList)
{
Monitor.PulseAll(arrayList); // We’re gonna change the state.
// We could also do Pulse.

arrayList.Add(item);
}


}


public void RemoveItem(int index) // Thread-safe method.
{
lock (arrayList)
{
Monitor.Pulse(arrayList);
arrayList.RemoveAt(index);
}


}

------解决方案--------------------
哦,那用了lock似乎就不用montior了啊,lock好简单
----------------------------------------------

lock(object)
{
//DoSomething();
}

等同于:

try
{
Monitor.Enter(object);
//DoSomething();
}
catch
{
throw;
}
finally //这个经常会忘掉,用lock 就简单了.
{
Monitor.Exit(object);
}