As per the singleton pattern,
public sealed class Singleton
{
static Singleton instance=null;
Singleton()
{
}
public void abc(){
}
public static Singleton Instance
{
get
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
the above is not thread-safe.Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern.
Confusion is Instance is static, how this can be null once it is called on UI thread or other threads?
EDIT
I meant to said that once i have called Singleton.Instance.abc();
Singleton.Instance should not be null until it is disposed manually. Right?
Control is passed to
ThreadAThreadAtrys to get theInstance, it is found to benull.Control is passed to
ThreadBThreadBtrys to get theInstance, it is found to benull.Control is passed to
ThreadAThreadAinstantiatesInstance.Control is passed to
ThreadBThreadBre-instantiatesInstance.Solution: You an use a
staticconstructor to ensure this doesn’t happen.