I have the following situation: I want to mutualy exclude access to an object.
So far I normaly would use a lock object
object lockObject = new object();
...
method1: lock(lockObject) { CODE1 }
Now I have also a method which can be called from another thread. It should not be blocked for unknown time, instead it should give an answer in a defined time.
In this case i would use a monitor, like
method2:
try{
Monitor.TryEnter(lockObject , 20000, ref lockTaken);
if (lockTaken) {CODE2}
}
catch(...){...}
finally
{
if (lockTaken) Monitor.Exit(timerLock);
}
Now my question is: can lock and monitor be mixed in such a way if the lockobject is the same and mutually exclude each other, or would it be needed to change every lock to a monitor.
So would both times the same token be "locked", or would the monitor create another token for the object then the lock?
At a glimpse I cannot see that the aplication runs in code of both at the same time. But I don't know if any timing issues can exist, where CODE1 and CODE2 are executed in parallel.
lock
keyword took a timeout somehow