This is what works...

I have often heard the argument that static methods in C# are thread safe because their parameters are instance values. Or something to that effect.

I never really accepted this nonsense but I heard it too many times and started to believe it.

Today, I saw something which has fully shown me that this is not true. When multiple threads can enter a method, the safest way and the least complex way to prevent concurrency is to let it be an instance method and let different instances of the object run on different threads.

Many guys may say otherwise. But I just saw a case where it clearly is not thread safe and I need to lock stuff to protect it.

What is the point of writing static methods and putting lock statements all over the code?

- Better for it to be instance methods and do away with this contention to begin with.

The best multi-threaded code is code where you split the work and share no resources, so stuff can actually run in parallel and do not have to deal with contention. If there is contention on any resource, then the locks should be there just to read/ write to it.

Comments

Popular posts from this blog

Tutorial: Using Google Cloud Storage from C# and .NET

Late 2008 Macbook only giving 1.5 gb/s speed with 6 gb/s Intel SSD?

The ridiculous interview experience