/// <summary> /// 速度快不阻塞线程、可能创建多个对象,只发布一个,使用在构造器没有副作用的时候 /// </summary> /// <returns></returns> public static Singletom GetSingletom() { if (null == instance) { Singletom temp = new Singletom(); Interlocked.CompareExchange(ref instance, temp, null); } return(instance); }
//双检锁技术 public static Singletom GetInstance() { if (null == instance) { Monitor.Enter(s_lock); if (null == instance) { Singletom temp = new Singletom(); //其他线程发现不为null,但是有可能对象的构造器还没有结束执行 Interlocked.Exchange(ref instance, temp); //将引用保存到值中 } Monitor.Exit(s_lock); } return(instance); }