首先我们要知道为什么要用这个
如果你需要异步操作的话,不影响前台UI操作的吗,那么就可以使用这个。更方便的进行异步操作。
同时可以跨线程调用其他的控件。
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 BackgroudWorkerTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string str = e.Argument.ToString();
for(int i=0;i<100;i++)
{
Thread.Sleep(100);
//该函数可以传递数字进度,还有文字信息给backgroundWorker1_ProgressChanged事件。触发backgroundWorker1_ProgressChanged
backgroundWorker1.ReportProgress(i,"百分比");
//int t = (i - 7) / (i-7); //测试 异常是否会在 complete事件中抓到
if (backgroundWorker1.CancellationPending == true)
{
e.Cancel = true; //这里设置 cancel未true,那么在backgroundWorker1_RunWorkerCompleted中可以获取到
break;
}
}
e.Result = "执行完成";//这里设定操作结果,但是有一个重点就是,如果 cancel被设置成true,那么backgroundWorker1_RunWorkerCompleted将无法通过e.Result获取结果
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
this.label1.Text = e.ProgressPercentage + e.UserState.ToString();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.progressBar1.Value = 0;// 可以在这里操作界面的控件
if (e.Error != null) // 如果dowork中报错,可以在这里获取到报错的事件进行处理
{
Type errorType = e.Error.GetType();
MessageBox.Show(e.Error.Message);
}
if (e.Cancelled)
{
MessageBox.Show("已关闭");
}
else
{
MessageBox.Show(e.Result.ToString());//cancelld==true,result将无法获取,会报错
}
}
private void button1_Click(object sender, EventArgs e)
{
if(!backgroundWorker1.IsBusy)//如果后台已经使用,再次点击无效
{ //这个方法会调用backgroundWorker1_DoWork
backgroundWorker1.RunWorkerAsync("test");//传递参数
}
//backgroundWorker1.ReportProgress(90);
//当操作中时,显示进度
while(backgroundWorker1.IsBusy)
{
progressBar2.Increment(1);
// Keep UI messages moving, so the form remains
// responsive during the asynchronous operation.
Application.DoEvents();
}
}
private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.WorkerReportsProgress = true;//设置BackgroundWorker 能否报告进度更新。如果是flase,那么backgroundWorker1.ReportProgress将无法使用
backgroundWorker1.WorkerSupportsCancellation = true;//设置是否可以取消异步操作
}
private void button2_Click(object sender, EventArgs e)
{
if(backgroundWorker1.WorkerSupportsCancellation)
{
backgroundWorker1.CancelAsync();//这个方法会设置backgroundWorker1.CancellationPending为true。但我们仍需要编写辅助代码在dowork中,手动取消事件操作
}
}
}
}