On design patterns: When should I use the singleton?
class Singleton
{
private static Singleton instance;
private Singleton() {}
Note that this code is not thread safe:
get
{
if (instance == null)
instance = new Singleton();
return instance;
}
One thread could enter the function, get past the test for null and then be suspended. A second thread could then start and get past the null test. From that point on, both threads will at some point create their own copy of the sungleton object, only one of which gets used.
This may not matter so much in a GC language like C#, but if the singleton controls rresources other than memory, then it does matter. You need to use the double-checked locking pattern to prevent it.