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); } }
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(object)
{
//DoSomething();
}等同于:try
{
Monitor.Enter(object);
//DoSomething();
}
catch
{
throw;
}
finally //这个经常会忘掉,用lock 就简单了.
{
Monitor.Exit(object);
}