SynchronizationAttribute snake-oil

I have now been asked twice why you wouldn’t just use the [Synchronization] attribute when you want to make a class thread-safe. I figured I’d share what little information I have on this topic to you since I happen to have an answer. (as opposed to “the” answer which I never have).


As the saying goes, “There is no such thing as a free lunch.” I never really understood this saying as a kid. I grew up in a poor neighborhood and got “free lunches” all the time. Being financially challenged, I used to laugh and say “well, this is free”. As I’ve gotten older, and much more financially stable, I realize that my tax dollars are paying for the lunches for other kids in other neighborhood — apparently they are eating very well.


The same holds true for this special attribute. If you may think you are getting thread-safty for free, I have some snake-oil to sell you. There are several problems with the SynchronizationAttribute. Take a look at the required signature for use of the synchronization attribute:


[Synchronization]
public class SuperSensativeClass :
System.Runtime.Remoting.Contexts.ContextBoundObject
{
// Implementation here
}


First, the attribute requires that you inherit from ContextBoundObject — wasting your single-inheritance chain. If you wanted it in your object your most primitive object in the inheritance chain would have to derive from this class, and then what if you didn’t want some other child classes to be context bound?


Second, suppose your class has several methods which don’t have thread-sensative data. What happens there? The CLR will still lock those methods since it has no idea what is thread-volatile and what isn’t. This can severely hamper performance.


If you are looking at thread-safety, you are likely trying to optimize the perceived performance of your application using multi-threading. The SynchronizationAttribute can actually have the exact opposite effect. Long story short, learn to use the synchronization primatives of System.Threading.

Be Sociable, Share!

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Post Navigation