The most common one:
The following is a reference fragment:
using System;
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
instance = new Singleton();
return instance;
}
}
}
This scenario is thread insecure under. NET, and each thread comes in and creates a different type instance.
The following is a. NET common language runtime's thread-safe single implementation mode:
The following is a reference fragment:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
It is a thread-safe pattern built on the capabilities of the common language runtime and is not applicable in other locales.
Based on this plus. NET support for generics, we can do a generic generic single example provider, the code is as follows:
The following is a reference fragment:
public class SingletonProvider where T : new()
{
SingletonProvider() { }
public static T Instance
{
get { return SingletonCreator.instance; }
}
class SingletonCreator
{
static SingletonCreator() { }
internal static readonly T instance = new T();
}
}
In this application, an instance of a singleton is guaranteed by the CLR to be created only when it is first referenced.
When it does not meet the need, such as: you need to do some other operations in the constructor to complete the initialization, then you can consider using the double-checked locking mode to implement.
Single example of a thread-safe line:
The following is a reference fragment:
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
When it comes to attention, the SyncRoot is locked here, not itself, which avoids the creation of deadlocks.
In other locales, double-checked locking does not necessarily work properly, because of the compiler's own problems, so the above implementation does not necessarily apply to other locales.