Skip to content

Making your objects thread-safe

April 6, 2007

Threads, light-weight processes, whatever term you prefer to use, once you start using them you will need to make sure any shared resources are made thread-safe. That is, multiple threads can use your shared resource without fear of corrupting data.

If you come from a Java background, you know that every object in Java is also a monitor and Java provides a synchronized keyword to protect methods that need exclusive access to its state.

In the .Net world, every heap object “can” have a lock (the details can be found in the resources). Instead of the synchronized keyword, C# has a lock keyword which is used to create critical sections. This keyword is really a short form for the singleton Monitor class’ Monitor.Enter(objand Monitor.Exit(obj) methods.

The recommended practice is to pass an instance of the current object (this) or the class (typeof(classname) for static members) to the critical-section-creation methods described above. This is not safe because any reference to the object can be passed into Monitor.Enter(obj) which a malicious coder could easily use to introduce deadlock and other synchronization errors.

The better method is to create a private System.Object member variable and lock onto that instead. Now your objects mutual exclusion is encapsulated and hidden from outside clients.


Safe Thread Synchronization


From → .Net, Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: