Winform 多线程--解决界面卡死问题
public class ThreadInvoker { /// <summary> /// 回调委托 带参数的 /// </summary> /// <param name="InvokerClass"></param> public delegate void CallbackFunc(InvokerClass InvokerClass); /// <summary> /// 回调委托的方法 /// </summary> public CallbackFunc AsynCallback; /// <summary> /// 线程 /// </summary> public Thread thread; /// <summary> /// 执行循环停止属性 /// </summary> public bool Stop = false; /// <summary> /// 休眠间隔 /// </summary> public int Sleep = 1000; public ThreadInvoker(CallbackFunc callback) { AsynCallback = callback; } public virtual void Start(ThreadStart ThreadStart) { thread = new Thread(ThreadStart); thread.Start(); } public virtual void Start(ParameterizedThreadStart ThreadStart) { thread = new Thread(ThreadStart); thread.Start(); } }
public class InvokerClass { public string String { get; set; } }
使用方法
public partial class Form1 : Form { public Form1() { InitializeComponent(); } ThreadInvoker ti; private void Form1_Load(object sender, EventArgs e) { } public void Excete(object InvokerClass) { InvokerClass _InvokerClass = InvokerClass as InvokerClass; while (!ti.Stop) { if (null == _InvokerClass) _InvokerClass = new InvokerClass(); _InvokerClass.String = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); ti.AsynCallback(_InvokerClass); Thread.Sleep(ti.Sleep); } } public void AsynUpdateTxtMethod(InvokerClass InvokerClass) { if (this.richTextBox1.InvokeRequired) { this.BeginInvoke(new ThreadInvoker.CallbackFunc(updatemethod), InvokerClass); } else { updatemethod(InvokerClass); } } public void updatemethod(InvokerClass InvokerClass) { this.richTextBox1.AppendText(InvokerClass.String + "\r\n"); this.richTextBox1.ScrollToCaret(); } /// <summary> /// 启动 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { ti = new ThreadInvoker(AsynUpdateTxtMethod); ti.Stop = false; ti.Start(new System.Threading.ParameterizedThreadStart(Excete)); } private void button2_Click(object sender, EventArgs e) { ti.Stop = true; } }
实现效果