Gagan
Gagan

Reputation: 29

Singleton class & multi-threading

Q: Can a singleton instance be broken when two threads from two different app-domains access the class?

I did some research and found below points relevant.

  1. A (.NET) Singleton is unique per App-domain - at least, the common Singleton pattern is. I suppose you could implement a per process Singleton, but I haven't thought about how it would really work....

  2. There would be 2 instances of your singleton.

  3. The input parameters (arguments) to the method are on the stack. Each thread have a separate stack. When the running thread switches, the stack is replaced.

Expert advice.?

Upvotes: 2

Views: 2398

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156948

Can a singleton instance be broken when two threads from two different app-domains access the class?

Yes. It is even possible from the same app domain. Consider this simple singleton implementation:

private static Singleton instance;
public static Singleton Instance
{
    if (instance == null)
    {
        instance = new Singleton();
    }

    return instance;
}

It is possible that both threads enter the property at the same time. In both cases instance == null is true and a new instance is created. One method already returns the created instance, the other resets the instance and returns that one a moment later. Singleton broken.

Much more to read on thread-safe singletons on the blog of Jon Skeet.

Upvotes: 3

Related Questions