调用Thread.sleep()方法在.NET锁语句中 [英] Calling Thread.Sleep() inside lock statement in .net

查看:252
本文介绍了调用Thread.sleep()方法在.NET锁语句中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在想,如果一个电话就已经acquiered监视器将临睡前释放锁的线程Threa.Sleep:

I was wondering if a call to Threa.Sleep on a thread that already acquiered a Monitor will release the lock before going to sleep:

object o = new object();
Montior.Enter(o);
Thread.Sleep(1000);
Monitor.Exit(o);



当线程被挂起 - 可以在其它线程获取 0

推荐答案

没有,锁也不会,如果你睡觉时释放出来。

No, the lock will not be released if you Sleep.

如果您希望以释放它,使用 Monitor.Wait(邻,超时);此外,您还可以使用这个从另一个线程的信号 - 另一个线程可以使用 Monitor.Pulse [全部] (按住锁),早于唤醒等待线程 。超时(它会重新收购的过程中锁,太)

If you want to release it, use Monitor.Wait(o, timeout); further, you can also use this to signal from another thread - another thread can use Monitor.Pulse[All] (while holding the lock) to wake the waiting thread earlier than "timeout" (it will re-acquire the lock in the process, too).

请注意:只要使用进入/退出,你应该考虑使用try /终于过 - 或。如果有异常情况发生,你的风险没有释放锁

Note that whenever using Enter/Exit, you should consider using try/finally too - or you risk not releasing the lock if an exception happens.

例如:

bool haveLock = false;
try {
    Monitor.Enter(ref haveLock);
     // important: Wait releases, waits, and re-acquires the lock
    bool wokeEarly = Monitor.Wait(o, timeout);
    if(wokeEarly) {...}
} finally {
    if(haveLock) Monitor.Exit(o);
}



另一个线程可以这样做:

Another thread could do:

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



这将目前微调的线程在对象上的等待(但什么都不做,如果没有对象是醒来)。强调:等待线程仍然必须等待脉冲的线程释放锁,因为它需要重新获取

Which will nudge any threads currently in a Wait on that object (but does nothing if no objects were waking). Emphasis: the waiting thread still has to wait for the pulsing thread to release the lock, since it needs to re-acquire.

这篇关于调用Thread.sleep()方法在.NET锁语句中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆