Singleton.cs 2.1 KB

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