Geeks With Blogs
Dennis Ecclestone's BLOG

When implementing the Singleton design pattern, we want to ensure that our code is thread-safe.  Alot of samples use the Mutex to ensure that the creation of the object is thread-safe.  A typical example is as follows;

Bad Example: Do not use this code

Public Class Singleton

    Private Shared _singleton As Singleton

    Private Shared _mu As New Mutex


    Private Sub New()


    End Sub


    Public Shared Function GetInstance() As Singleton



            If _singleton Is Nothing Then

                _singleton = New Singleton

            End If



        End Try

        Return _singleton

    End Function

End Class

This seems very reasonable, but there is a far better way which to implement this in .NET. 

Good Example – Using a shared public field

Public NotInheritable Class Singleton

    Public Shared ReadOnly Instance As New Singleton


    Private Sub New()


    End Sub

End Class

Good Example – Using a shared property to access a private shared field

Public NotInheritable Class Singleton2

    Private Shared ReadOnly _instance As New Singleton2


    Private Sub New()


    End Sub


    Public Shared ReadOnly Property Instance() As Singleton2


            Return _instance

        End Get

    End Property

End Class

The .NET framework guarantees that the initialization of static (shared) members will be thread-safe.  There are a couple of important points;

  • The class needs to be sealed (i.e. use NotInheritable for VB.NET).
  • The constructor needs to be private to prevent instantiation of the class.

If you compare either of these implementations with the Mutex method, you’ll find that there is a massive performance hit by using the Mutex.  I did a test where I accessed a Singleton 10000000 times using each of these three approaches;

Singleton with Mutex: 00:00:21.6210896
Singleton: 00:00:00.0500720           (432 times faster than mutex)
Singleton2: 00:00:00.1201728         (180 times faster than mutex)

The results are quite clear.  Either of these approaches are alot faster than using a Mutex.

You can find more information here

There are also a couple of good articles on MSDN.


Posted on Thursday, December 22, 2005 2:29 PM | Back to top

Comments on this post: Singleton Design Pattern for .NET

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Dennis Ecclestone | Powered by: