【发布时间】:2012-01-17 14:04:41
【问题描述】:
我用 C# 编码已经有一段时间了,但是这个锁定顺序对我来说没有任何意义。我对锁的理解是,一旦用lock(object)获得锁,代码就得退出锁作用域才能解锁对象。
这让我想到了手头的问题。我剪掉了下面的代码,它恰好出现在我的代码中的动画类中。该方法的工作方式是将设置传递给该方法并进行修改,然后再传递给另一个重载方法。另一个重载方法会将所有信息传递给另一个线程,以某种方式处理并实际为对象设置动画。动画完成后,另一个线程调用OnComplete 方法。这实际上都完美工作,但我不明白为什么!
另一个线程能够调用OnComplete,获得对象上的锁并向原始线程发出信号,它应该继续。由于对象被锁定在另一个线程中,此时代码是否应该冻结?
因此,在修复我的代码时不需要帮助,而是需要澄清它的工作原理。任何理解方面的帮助表示赞赏!
public void tween(string type, object to, JsDictionaryObject properties) {
// Settings class that has a delegate field OnComplete.
Tween.Settings settings = new Tween.Settings();
object wait_object = new object();
settings.OnComplete = () => {
// Why are we able to obtain a lock when the wait_object already has a lock below?
lock(wait_object) {
// Let the waiting thread know it is ok to continue now.
Monitor.Pulse(wait_object);
}
};
// Send settings to other thread and start the animation.
tween(type, null, to, settings);
// Obtain a lock to ensure that the wait object is in synchronous code.
lock(wait_object) {
// Wait here if the script tells us to. Time out with total duration time + one second to ensure that we actually DO progress.
Monitor.Wait(wait_object, settings.Duration + 1000);
}
}
【问题讨论】:
标签: c# .net multithreading locking