SingletonTemplate.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System;
  2. using System.Threading;
  3. using System.Windows.Forms;
  4. namespace StandardLibrary
  5. {
  6. //单例模式
  7. public class SingletonTemplate<T> where T : class, new()
  8. {
  9. // Nested Types
  10. public delegate void LogHandler(ListBox logListBox, string strLog);
  11. // Events
  12. public event LogHandler LogEvent;
  13. // Fields
  14. protected bool m_bRunThread;
  15. private static T m_instance;
  16. private ListBox m_LogListBox;
  17. private Thread m_thread;
  18. private static readonly object syslock;
  19. static SingletonTemplate()
  20. {
  21. SingletonTemplate<T>.syslock = new object();
  22. }
  23. public SingletonTemplate()
  24. {
  25. this.m_LogListBox = null;
  26. this.m_thread = null;
  27. }
  28. public static T GetInstance()
  29. {
  30. if (SingletonTemplate<T>.m_instance == null)
  31. {
  32. object syslock = SingletonTemplate<T>.syslock;
  33. lock (syslock)
  34. {
  35. if (SingletonTemplate<T>.m_instance == null)
  36. {
  37. SingletonTemplate<T>.m_instance = Activator.CreateInstance<T>();
  38. }
  39. }
  40. }
  41. return SingletonTemplate<T>.m_instance;
  42. }
  43. public void SetLogListBox(ListBox logListBox)
  44. {
  45. this.m_LogListBox = logListBox;
  46. }
  47. public void ShowLog(string strLog)
  48. {
  49. if ((this.LogEvent != null) && (this.m_LogListBox != null))
  50. {
  51. this.LogEvent(this.m_LogListBox, strLog);
  52. }
  53. }
  54. public void StartMonitor()
  55. {
  56. if (this.m_thread == null)
  57. {
  58. this.m_thread = new Thread(new ThreadStart(this.ThreadMonitor));
  59. }
  60. if (this.m_thread.ThreadState > System.Threading.ThreadState.Running)
  61. {
  62. this.m_bRunThread = true;
  63. this.m_thread.Start();
  64. }
  65. }
  66. public void StopMonitor()
  67. {
  68. if (this.m_thread != null)
  69. {
  70. this.m_bRunThread = false;
  71. if (!this.m_thread.Join(0x1388))
  72. {
  73. this.m_thread.Abort();
  74. }
  75. this.m_thread = null;
  76. }
  77. }
  78. public virtual void ThreadMonitor()
  79. {
  80. while (this.m_bRunThread)
  81. {
  82. Thread.Sleep(100);
  83. break;
  84. }
  85. }
  86. }
  87. }