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) { //记录错误日志追踪文件 } } } }