当构建一个图形化的Windows Form桌面应用程序并且需要执行在应用程序主UI线程之外的线程中长时间的任务时,BackgroundWorker类就很有用了。
要使用BackgroundWorker,我们只需要告诉它希望在后台执行那个方法并且调用RunWorkerAsync()即可
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
int a = int.Parse(textBox1.Text.Trim());
int b = int.Parse(textBox2.Text.Trim());
Add ad = new Add(a,b);
backgroundWorker1.RunWorkerAsync(ad);
} private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Add args=(Add)e.Argument;
for (int i = ; i < ; i++)
{
Thread.Sleep();
backgroundWorker1.ReportProgress(i*);
} e.Result = args.a + args.b;
} private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
label1.Text = e.Result.ToString();
} private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
}
public class Add
{
public int a;
public int b;
public Add(int a, int b)
{
this.a = a;
this.b = b;
} }