Peter Bahaa's Blog

Business and Technical Articles

Implementing Multithreaded Singleton Class

August 17
by Peter Bahaa 17. August 2010 02:46

You are building an application in C#. You need a class that has only one instance, and you need to provide a global point of access to the instance. You want to be sure that your solution is efficient and that it takes advantage of the Microsoft .NET common language runtime features. You may also want to make sure that your solution is thread safe.

Multithreaded Singleton

Static initialization is suitable for most situations. When your application must delay the instantiation, use a non-default constructor or perform other tasks before the instantiation, and work in a multithreaded environment, you need a different solution.

The following implementation allows only a single thread to enter the critical area, which the lock block identifies, when no instance of Singleton has yet been created:

 

1 using System; 2 3 public sealed class Singleton 4 { 5 private static volatile Singleton instance; 6 private static object syncRoot = new Object(); 7 8 private Singleton() {} 9 10 public static Singleton Instance 11 { 12 get 13 { 14 if (instance == null) 15 { 16 lock (syncRoot) 17 { 18 if (instance == null) 19 instance = new Singleton(); 20 } 21 } 22 23 return instance; 24 } 25 } 26 }

volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed

The class is marked sealed to prevent derivation, which could add instances

Originally taken from http://privacy.microsoft.com/en-us/default.mspx

I hope this helps :)

Tags:

C# | Tips & Tricks | Best Practices

Comments

9/19/2011 3:42:27 AM #

The singleton pattern must be carefully constructed in multi-threaded applications.

charge off

9/24/2011 8:05:20 AM #

What would most people do without the awesome concepts you discuss on this website? Who has got the tolerance to deal with critical topics with regard to common visitors like me? My spouse and i and my girlfriends are very happy to have your blog among the kinds we regularly visit. Hopefully you know how a great deal we enjoy your efforts! Best wishes from us all.

Twyla

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar