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 :)