Thread-Safe Lazy Singleton Implementation in .NET 4
It has been a while since I needed to develop a singleton in .NET, and now that I am working in .NET 4, I thought it was a good time to revisit the implementation and take advantage of new language features.
So without much fanfare, here it is:
1Public NotInheritable Class MySingleton 2 3#Region " Thread-Safe Lazy Singleton " 4 5 Private Shared _instance As Lazy(Of MySingleton) = New Lazy(Of MySingleton)(Function() New MySingleton()) 6 7 ''' <summary> 8 ''' Hide the constructor 9 ''' </summary> 10 ''' <remarks></remarks> 11 Private Sub New() 12 ' nothing to do 13 End Sub 14 15 ''' <summary> 16 ''' Singleton instance 17 ''' </summary> 18 ''' <value></value> 19 ''' <returns></returns> 20 ''' <remarks></remarks> 21 Public Shared ReadOnly Property Instance As MySingleton 22 Get 23 Return _instance.Value 24 End Get 25 End Property 26 27#End Region 28 29End Class
The .NET 4
Lazy class by default ensures that the singleton is thread-safe.
If you use the
Lazy class and do not pass in any parameters, it will construct the type automatically for you… which means that the class must have a public constructor method with no parameters. By passing a value factory delegate into the constructor of the
Lazy class, we can keep our constructor private and thereby force others to use our Instance property and truly make a Singleton.