while using the singleton pattern, only one instance is created in multi threading?
Using threadsafe singleton class will guarantee that only one instance is created.
public sealed class Singleton
{
private static Singleton singleton = null;
private static readonly object singletonLock = new object();
private Singleton() {}
public static Singleton GetInstance()
{
lock (singletonLock)
{
ак (singleton == null)
{
singleton = new Singleton();
}
return singleton ;
}
}
}
Issue will raise only when the creation of first instance.
Using lock() will provide us the thread safe to avoid execution of two threads at a same time to create instance.
Again we are verifying the (singletonobject == null) so it will guarantee that only once instance will be created.
double check option will be full proof for our class.
Вашият коментар