Singleton Pola Hanya Satu Instance Diciptakan dalam Multi Threading

semasa menggunakan pola tunggal, hanya satu contoh dicipta dalam multi threading?

Dengan menggunakan kelas threadsafe tunggal akan menjamin bahawa hanya satu contoh dicipta.

public sealed class Singleton
{
private static Singleton singleton = null;
private static readonly object singletonLock = new object();

private Singleton() {}
public static Singleton GetInstance()
{
lock (singletonLock)
{
jika (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.

Tinggalkan Reply

Anda boleh menggunakan tag HTML ini

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>