I want to reask my previous question how to obtain a lock in two places but release on one place? because it seems too old and noone sees my updated code.
The question is - is my code correct and how to fix it if not? I've tried similar code in the application and it hangs, but I don't now why, so I guess probably my code still wrong...
public void obtainLock() {
if (needCallMonitorExit == false) {
Monitor.Enter(lockObj);
needCallMonitorExit = true;
}
// doStuff
}
public void obtainReleaseLock() {
try {
lock (lockObj) {
// doAnotherStuff
}
} finally {
if (needCallMonitorExit == true) {
needCallMonitorExit = false;
Monitor.Exit(lockObj);
}
}
}
One of my methods should obtain the lock. another method should obtain the same lock and release it. sometimes just obtainReleaseLock
is called. sometimes obtainLock
is called (probably several times) and after a while obtainReleaseLock
is called. These two methods are always called from the same thread, however lockObj
is used in another thread for synchronization.