LazySingleton.cs 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace parkMonitor.server.WebThread
  9. {
  10. class LazySingleton
  11. {
  12. private static TcpListener listener = null;
  13. private static readonly object syncRoot = new object();
  14. private LazySingleton()
  15. {
  16. }
  17. public static TcpListener GetInstance(IPAddress localAddr,Int32 port)
  18. {
  19. //第一重判断,先判断实例是否存在,不存在再加锁处理
  20. if (listener == null)
  21. {
  22. //加锁的程序在某一时刻只允许一个线程访问
  23. lock (syncRoot)
  24. {
  25. //第二重判断
  26. if (listener == null)
  27. {
  28. listener = new TcpListener(localAddr, port); //创建单例实例
  29. }
  30. }
  31. }
  32. return listener;
  33. }
  34. }
  35. }