1、定义线程类及内部事件
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Windows.Forms; namespace ThreadSample { public delegate void ThreadEventHandler(object sender, EventArgs e); public class myThread { //线程执行开始调用事件 public event ThreadEventHandler RequestEvent; //线程执行结束调用事件 public event ThreadEventHandler CompletedEvent; //是否允许执行线程中具体任务 public bool isExecute = false; //线程名称 private string threadName = "线程"; //string.Empty; public string ThreadName { get { return threadName; } } public void Start() { try { //执行前调用事件 RequestEvent(this, null); if (isExecute) { //执行任务 Random seed = new Random(DateTime.Now.Millisecond); int sleepTime = seed.Next(100, 300); Thread.Sleep(sleepTime); } threadName += Thread.CurrentThread.ManagedThreadId.ToString(); //执行后调用事件 CompletedEvent(this, null); } catch (Exception ex) { //记录错误日志追踪文件 } } } }
2、在外部调用线程,并添加线程事件内容,及其监视器实现同步
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; namespace ThreadSample { public partial class frmApp : Form { public frmApp() { InitializeComponent(); } private void btnExit_Click(object sender, EventArgs e) { Environment.Exit(0); } private void btnRun_Click(object sender, EventArgs e) { try { int threadCount = 10; this.tbMonitor.Clear(); //显示监视线程的信息 myThread[] threadArray = new myThread[threadCount]; Thread td = null; for (int i = 0; i < threadCount; i++) { threadArray[i] = new myThread(); threadArray[i].RequestEvent += frmApp_RequestEvent; threadArray[i].CompletedEvent += frmApp_CompletedEvent; td = new Thread(threadArray[i].Start); td.Start(); } } catch (Exception ce) { MessageBox.Show(ce.ToString()); } } //记录线程信息 private delegate void RecordsEventHandler(object sender, EventArgs e); //依据线程调用次方法的先后显示信息 private void frmApp_CompletedEvent(object sender, EventArgs e) //sender太泛,可以给准确名字(myThread) { if (this.tbMonitor.InvokeRequired) { this.tbMonitor.Invoke(new RecordsEventHandler(frmApp_CompletedEvent), new object[] { sender, e }); } else { try { Monitor.Enter(this.tbMonitor); //同步机制,指定对象获取排它锁 //具体操作 this.tbMonitor.Text += (sender as myThread).ThreadName + "--- ---" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffff ") + Environment.NewLine; } catch (Exception ex) { MessageBox.Show(ex.ToString()); //记录错误日志追踪文件 } finally { Monitor.Exit(this.tbMonitor); //同步机制,指定对象释放排它锁 } } } private void frmApp_RequestEvent(object sender, EventArgs e) { //是否允许执行线程中具体任务 (sender as myThread).isExecute = true; } } }
注意:监视器实现同步的对象是否必须调用Invoke()方法。