using System; using System.Threading; using System.Windows.Forms; namespace StandardLibrary { //单例模式 public class SingletonTemplate where T : class, new() { // Nested Types public delegate void LogHandler(ListBox logListBox, string strLog); // Events public event LogHandler LogEvent; // Fields protected bool m_bRunThread; private static T m_instance; private ListBox m_LogListBox; private Thread m_thread; private static readonly object syslock; static SingletonTemplate() { SingletonTemplate.syslock = new object(); } public SingletonTemplate() { this.m_LogListBox = null; this.m_thread = null; } public static T GetInstance() { if (SingletonTemplate.m_instance == null) { object syslock = SingletonTemplate.syslock; lock (syslock) { if (SingletonTemplate.m_instance == null) { SingletonTemplate.m_instance = Activator.CreateInstance(); } } } return SingletonTemplate.m_instance; } public void SetLogListBox(ListBox logListBox) { this.m_LogListBox = logListBox; } public void ShowLog(string strLog) { if ((this.LogEvent != null) && (this.m_LogListBox != null)) { this.LogEvent(this.m_LogListBox, strLog); } } public void StartMonitor() { if (this.m_thread == null) { this.m_thread = new Thread(new ThreadStart(this.ThreadMonitor)); } if (this.m_thread.ThreadState > System.Threading.ThreadState.Running) { this.m_bRunThread = true; this.m_thread.Start(); } } public void StopMonitor() { if (this.m_thread != null) { this.m_bRunThread = false; if (!this.m_thread.Join(0x1388)) { this.m_thread.Abort(); } this.m_thread = null; } } public virtual void ThreadMonitor() { while (this.m_bRunThread) { Thread.Sleep(100); break; } } } }