views:

580

answers:

3

I have an ASP.NET webpage running under IIS that uses a common assembly that contains a singleton class. Should I implement a locking mechanism on the singleton to make it thread-safe? Or, will any connection to the webserver use the same instance of the singleton?

Hopefully I'm asking this coherently.

+3  A: 

If it's a static singleton... no, it's not thread safe. It's shared across all threads that are hitting that instance of the app (so multi-requests will share it).

However, what you're using it for might not need thread safety necessarily.

Timothy Khouri
+2  A: 

The usual pattern for .NET singletons creates a single instance per app domain. The usual situation in asp.net is that you have multiple threads running through the same app domain. This means you could very well have multiple threads running code in your singleton at the same time.

You have to examine the singleton and determine (to the best of your abilities koffreflectorkoff) if it is thread safe or not. If it keeps and modifies shared resources, or if it encapsulates some kind of state which is stored between method calls, be careful.

You might want to wrap the singleton within a second singleton which uses locks before delegating its calls to the one you don't have control over. That way you could have finer control over locking rather than block every call to the singleton using a single lock. It would also give you the benefit of centralizing the location of the threading code...

Will
A: 

In .NET it is possible to implement a Thread-safe Singleton without using locks.

Petter Wigle
-1. The methods would need to have locks if so required. This link doesn't get into those details (only about how to create the singleton class itself, not its functionality).
Ricardo Villamil
+1. This comment doesn't deserve -1. Indeed, the methods might need locks, but this is separate from the implementation of the singleton pattern itself IMO.
Ben Aston