Singleton.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Threading;
  3. using Fort23.UTool;
  4. namespace Utility
  5. {
  6. public class Singleton<T> : IDisposable where T : new()
  7. {
  8. static object m_lock = new object();
  9. #if COMBAT_SERVER
  10. private static Map<int, T> _threadingInstance = new Map<int, T>();
  11. #endif
  12. #if !COMBAT_SERVER
  13. protected static T m_instance;
  14. public static T Instance
  15. {
  16. get
  17. {
  18. if (m_instance == null)
  19. {
  20. lock (m_lock)
  21. {
  22. if (m_instance == null)
  23. {
  24. m_instance = new T();
  25. }
  26. }
  27. }
  28. return m_instance;
  29. }
  30. set { m_instance = value; }
  31. }
  32. public virtual void Dispose()
  33. {
  34. ProDispose();
  35. Instance = (T) (object) null;
  36. }
  37. #else
  38. public static T Instance
  39. {
  40. get
  41. {
  42. int id = Thread.CurrentThread.ManagedThreadId;
  43. if (_threadingInstance.TryGetValue(id, out T VALUE))
  44. {
  45. return VALUE;
  46. }
  47. lock (_threadingInstance)
  48. {
  49. if (_threadingInstance.TryGetValue(id, out T VALUE2))
  50. {
  51. return VALUE2;
  52. }
  53. else
  54. {
  55. // LogTool.Log("新建示例"+id+"__"+typeof(T));
  56. T iInstance = new T();
  57. _threadingInstance.Add(id, iInstance);
  58. return iInstance;
  59. }
  60. }
  61. }
  62. }
  63. public virtual void Dispose()
  64. {
  65. ProDispose();
  66. lock (_threadingInstance)
  67. {
  68. int id = Thread.CurrentThread.ManagedThreadId;
  69. _threadingInstance.Remove(id);
  70. }
  71. }
  72. #endif
  73. protected virtual void ProDispose()
  74. {
  75. }
  76. }
  77. }