using System; using System.Threading; using System.Windows.Forms; namespace { public class Form1 : Form { public Form1() { InitializeComponent(); } private delegate void ControlEventHandler(string str); private Worker worker = new Worker(); private void Form1_Load(object sender, EventArgs e) { this.worker.MessagingEvent += this.Worker_MessagingEvent; } private void Worker_MessagingEvent(string message) { //检查是否需要跨线程,如果需要,将方法加入委托,如果不需要直接执行方法。 if (this.textBox1.InvokeRequired) { ControlEventHandler controlEventHandler = new ControlEventHandler(Worker_MessagingEvent); this.textBox1.Invoke(controlEventHandler, new object[] { message }); } else { this.textBox1.Text = message; } } private void button1_Click(object sender, EventArgs e) { //创建线程,避免堵塞GUI线程。 this.NewThread(); } private void NewThread() { //创建线程,避免堵塞GUI线程。 ThreadStart ts = new ThreadStart(Work); Thread t = new Thread(ts); t.Start(); }
private void Work() { //在新的线程中,需要执行的方法。 this.worker.Work(); } }
public class Worker { public event Messaging MessagingEvent; public delegate void Messaging(string message); public void Work() { // TODO... MessagingEvent("Hello World!"); } } }
原文:https://www.cnblogs.com/vicky2021/p/14813036.html