Reputation: 29
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.
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....
There would be 2 instances of your singleton.
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
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