当子线程操作主线程(UI线程)的控件时,可能会造成阻塞或冲突;使用委托就可以避免。
public FrmTelnet() { Control.CheckForIllegalCrossThreadCalls = false; InitializeComponent(); } // 线程安全输出 public delegate void showInfoDelegate(string str); private void showInfo(string str) { if (txtInfo.InvokeRequired) { showInfoDelegate la = new showInfoDelegate(showInfo); txtInfo.Invoke(la, str); return; } if (txtInfo.TextLength > 100000) { txtInfo.Text = ""; } txtInfo.AppendText(str.Trim() + System.Environment.NewLine); }
简单事件触发备忘
// 消息事件 public delegate void EventInfo(object sender, string info); public event EventInfo OnEventInfo; // 触发消息 private void showInfo(string str) { OnEventInfo(this, str); } ///////// 调用 HttpServer httpServer = new HttpServer(); httpServer.OnEventInfo += eventInfo; private void eventInfo(object sender, string info) { // 处理 }
快捷线程创建备忘
Thread ThreadListener = new Thread(() => { while (true) { try { } catch { } } }); ThreadListener.IsBackground = true; ThreadListener.Start();