代码如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace TestBackGroundWorkerCompleteEvent { public partial class Form1 : Form { public Form1() { InitializeComponent(); backgroundWorker.DoWork += OnDoWork; backgroundWorker.RunWorkerCompleted += OnRunWorkerCompleted; } static BackgroundWorker backgroundWorker = new BackgroundWorker(); private void OnDoWork(object sender, DoWorkEventArgs e) { Thread.Sleep(1000); e.Result = "任务完成!";//传递结果 } private void OnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { Action action = new Action(() => { textBox.Text = e.Result.ToString(); }); this.textBox.BeginInvoke(action); //在控件创建的线程更新控件,必须要执行上面的委托才行 } private void btnStart_Click(object sender, EventArgs e) { backgroundWorker.RunWorkerAsync(); } } }
演示如下: