rulururu

post Monitor class: Thread Safety

April 10th, 2008

Filed under: .NET — Kai @ 7:57 am

The Monitor class controls access to objects by granting a single thread a lock for an object. Object locks provide the ability to restrict access to a block of code, commonly called a critical section. While a thread owns the lock for an object no other thread can acquire the lock for the object. Additionally, the Monitor class can be used to ensure that no other thread can access a section of application code being executed by the lock owner, unless the other thread is executing the code using a different locked object.

I ever wondered what the difference between using a lock statement, versus using a Montior.Enter / Monitor.Exit clause is? Actually there’s a few, but the main one is that a lock statement is inherently thread safe, where-as a Montior is not. So -

try {
Monitor.Enter(_lock);
DoThreadSafeCode();
} finally {
Monitor.Exit(_lock);
}

is essentially the same as -

lock (_lock) {
DoThreadSafeCode();
}

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

ruldrurd
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)