第一种:双if + lock
public class Singleton { private static Singleton _Singleton = null; private static object Singleton_Lock = new object(); public static Singleton CreateInstance() { if(_Singleton == null) //双if+lock { lock (Singleton_Lock) { Console.WriteLine("路过……"); if(_Singleton == null) { Console.WriteLine("被创建……"); _Singleton = new Singleton(); } } } } }
//测试: TaskFactory taskFactory = new TaskFactory(); List<Task> taskList = new List<Task>(); for(int i=0;i<5;i++) { taskList.Add(taskFactory.StartNew( ()=>{ Singleton singleton = Singleton.CreateInstance();})); }
第二种:利用静态变量实现单例模式
public class SingletonThird { private static SingletonThird _SingletonThird = new SingletonThird(); public static SingletonThird CreateInstance() { return _SingletonThird; } }
第三种:利用静态构造函数实现单例模式
public class SingletonSecond { private static SingletonSecond _SingletonSecond = null; static SingletonSecond() { _SingletonSecond = new SingletonSecond(); } public static SingletonSecond CreateInstance() { return _SingletonSecond; } }