March 16, 2006

Manual Locking With Monitors

When we want to use a timed 'lock' we can not use the normal lock statement, we have to use the monitor directly.
private object someLock = new object();
// Here we need to execute something within a Timeout period
// but we could exceed the timeout just waiting for the lock on our object!
algo = null;
int start = System.Environment.TickCount;
bool lockAquired = Monitor.TryEnter(someLock, timeout);
if (lockAquired)
    int elapsedTime = (System.Environment.TickCount-start);
    // Did we use any time up waiting for the lock? Take it off the original timeout 
    // new timeout = original timeout - time expired obtaining the lock
    int timeLeft = timeout - elapsedTime;
    if (timeLeft > 0)
        DoSomething(timeLeft, out algo);

No comments: