using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace centralController.WebServer { class LazySingleton { private static TcpListener listener = null; private static readonly object syncRoot = new object(); private LazySingleton() { } public static TcpListener GetInstance(IPAddress localAddr,Int32 port) { //第一重判断,先判断实例是否存在,不存在再加锁处理 if (listener == null) { //加锁的程序在某一时刻只允许一个线程访问 lock (syncRoot) { //第二重判断 if (listener == null) { listener = new TcpListener(localAddr, port); //创建单例实例 } } } return listener; } } }