VCK
VCK

Reputation: 3

Monitor Class in Depth

All,

Could you explain me about Monitor Class, esp following code in more detail?

if (Monitor.TryEnter(CashDrawers.lockObject))
    {
        try
        {
            // Work here                    
        }
        finally
        {
            Monitor.Exit(lockObject);
        }
    }

Thanks, CK

Upvotes: 0

Views: 58

Answers (1)

Kenneth Ito
Kenneth Ito

Reputation: 5261

Not sure if this is what you're looking for but...

The code you posted in your question is the non blocking version of

lock(CashDrawers.LockObject)
{
     //work here
}

Meaning that it will only do it's "work" if it is able to acquire the lock on the first try. If something else already has the lock, then your code won't do anything. I'm assuming this code is written within the CashDrawers class, otherwise you probably have a transcription error in that you need to Moniter.Exit on the same object that you Entered on.

Are you looking for an explanation on synchronization in general? If so that's beyond the scope of what I can write in an answer. Please check out http://www.albahari.com/threading/part2.aspx for some general synchronization info in .net.

Upvotes: 1

Related Questions