Unfortunately, the sample in this article (I refer to advice of
vivekse) is not thread-safe, but thread-safety is much more important for singletons than anywhere else.
Look at this article:
http://www.dofactory.com/Patterns/PatternSingleton.aspx#_self1[
^].
Locate the class
Singleton
and look at the "not thread safe" comment:
class Singleton {
private static Singleton _instance;
protected Singleton() { }
public static Singleton Instance() {
if (_instance == null)
_instance = new Singleton();
return _instance;
}
}
It looks like this comment and its placement suggests that thread safety could be provided by locking of the method returning its instance (I will also improve usability by converting it to a property:
class Singleton {
private static Singleton _instance;
private static object SignletonLock = new object();
protected Singleton() { }
public static Singleton Instance() {
get {
if (_instance == null)
lock(SignletonLock)
_instance = new Singleton();
return _instance;
}
}
}
Will it resolve the issue? Of course not!
In real life
class Singleton
is not such an empty class, it has to have members which might be accessed from different threads.
As this is a singleton, all threads will work with the same object, accessing same very members of the same instance in competition.
So, to make it thread safe, one need to make sure every shared resource in the singleton instance is interlocked. It will require one or more extra lock objects like
SingletonLock
.
Better yet, you may need to use
System.Threading.ReaderWriterLockSlim
instead of simple
lock
. This is important when threads often need read access to some singleton and much less need write (modification) access. This situation is quite typical, and
ReaderWriterLockSlim
deals with it with much better thoughput, because multiple threads can really allowed to read at the same time. Please see Microsoft help on
System.Threading.ReaderWriterLockSlim
complete with very clear code sample.