Pattern singleton thread safe en C# : c’est facile
Posted by Olivier on 20/06/2006
Lu ici : http://www.dofactory.com/Patterns/PatternSingleton.aspx
Voici la manière classique d’écrire un pattern singleton thread-safe en C# :
class MySingleton
{
private static MySingleton instance;
// Lock synchronization object
private static object syncLock = new object();
private MySingleton() { DoSomething(); }
public static MySingleton Instance
{
get
{
// Support multithreaded applications
// through 'Double checked locking'
// pattern which (once the instance
// exists) avoids locking each
// time the method is invoked
if (instance == null)
{
lock (syncLock)
{
if (instance == null)
instance = new MySingleton();
}
}
return instance;
}
}
}
Et maintenant, voici la manière “.NET” d’écrire ce même singleton :
class MySingleton
{
// Static members are lazily initialized.
// .NET guarantees thread safety for
// static initialization
private static readonly MySingleton instance =
new MySingleton();
// Constructor (private)
private MySingleton() { DoSomething(); }
public static MySingleton Instance { get { return instance; } }
}
ça marche parce que “private static readonly” entraîne :
- Initialisation paresseuse
- Thread-safety garantie par .NET pour les initialisations statiques.
C’est pas beau ça ?
Ant said
Merci ça m’a trop aidé dans un développement dans un contexte multithreadé, préemptif avec intropsection multiprotocole.
Par contre il faut lire la ligne :
public static Instance { get { return instance; } }
commme :
public static MySingleton
Instance { get { return instance; } }
Olivier said
Eh Antoine, n’en fais pas trop quand même !
zoopslick said
People who illegally download films and music will be cut off from the internet under new legislative proposals to be unveiled next week.Internet service providers (ISPs) will be legally required to take action against users who access pirated material, The Times has learnt