No, the lock will not be released if you sleep.
If you want to free it, use Monitor.Wait(o, timeout) ; in addition, you can also use this for a signal from another thread - another thread can use Monitor.Pulse[All] (holding the lock) to wake the waiting thread before the timeout (it will also close the lock again in this process )
Please note that whenever you use Enter / Exit, you should also use try / finally - or you are not at risk of releasing the lock if an exception occurs.
Example:
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 can do:
lock(o) { Monitor.PulseAll(o); }
Which will push any threads currently in Wait on this object (but will do nothing if the objects do not wake up). Emphasis: the waiting thread still has to wait until the impulse thread releases the lock, as it needs to be re-acquired.
source share