A propos du singleton en dotnet
Bonsoir,
J'ai une petite intérrogation à propos de la création de singleton en dotnet.
Personellement je fais toujours comme cela :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
public class Toto
{
private Toto() { }
private static Toto sInstance;
private static readonly object sSync = new object();
public static Toto Instance {
get {
if (sInstance == null) {
lock(sSync) {
if (sInstance == null) {
sInstance = new Toto();
}
}
}
return sInstance;
}
}
} |
Or au boulot je vois souvent cela :
Code:
1 2 3 4 5 6 7 8
|
public class Toto {
private Toto() {
}
public static Toto Instance = new Toto();
} |
J'ai effectué quelques tests la seconde méthode semble thread safe, et est aussi plus rapide.
Qu'en pensez vous ? Avez vous déjà utilisé cette "formulation" pour les singleton en dotnet ?
Merci