由于作者水平有限,如有错误请指正
下面的只是大概演示的例子,为了简单,代码安全校验不考虑
UI窗体如下:
Form1代码如下:
public partial class Form1 : Form
{
BackgroundWorker backgroundWorker = new BackgroundWorker();
public Form1()
{
InitializeComponent();
Console.WriteLine("UI初始化线程Id:" + Thread.CurrentThread.ManagedThreadId);
backgroundWorker.WorkerReportsProgress = true; //设置可以发消息,必须,不然没用
backgroundWorker.DoWork += BackgroundWorker_DoWork; //干活的方法,子线程发送消息
backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged; //主线程接收消息,并更新UI
}
//或者子线程的消息,并更新到UI
private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine("UI接收消息线程Id:" + Thread.CurrentThread.ManagedThreadId);
string receviceMsg = e.UserState as string;
this.textBox1.Text= receviceMsg;
}
//子线程发送消息
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
string inputMessage = e.Argument as string; //获取入参
Console.WriteLine("BackgroundWorker子线程Id:" + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(1000);
backgroundWorker.ReportProgress(1, inputMessage+"BackgroundWorker发送消息啦");
}
private void button1_Click(object sender, EventArgs e)
{
//异步启动并传达参数
backgroundWorker.RunWorkerAsync("传入的消息:");
}
}
其中BackgroundWorker_DoWork方法是子线程发消息的方法
BackgroundWorker_ProgressChanged方法是接收子线程消息的方法
运行结果如下:
注意观察线程Id的输出
当然BackgroundWorker还有取消,完成,重试和捕获异常的逻辑,具体可以参考博客: