BackgroundWorker 简介
BackgroundWorker 是一个用于在后台执行操作的组件。它提供了一种简单的方法来在用户界面线程之外执行耗时的任务,同时保持用户界面响应。
BackgroundWorker 主要用于在后台处理较长时间运行的任务,以避免阻塞用户界面(UI)线程。例如,当你需要执行某个复杂的计算、下载大文件、执行数据库操作或与远程服务器通信时,可以使用 BackgroundWorker 来确保这些任务在后台进行而不会冻结用户界面。
简单示例
例子1:执行单一耗时操作
// Form1.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (BackgroundWorker backgroundWorker = new BackgroundWorker())
{
backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
backgroundWorker.RunWorkerAsync(); // 可以传入参数
}
// 后续过程(不会被 BackgroundWorker 阻塞,即不会等待其完毕再执行)
// ...
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
//e.Argument // 可以取得传入的参数
// 模拟耗时操作
//...
string result = "...";
// 传递结果
e.Result = result;
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
textBox1.Text = e.Result.ToString(); // 输出结果
}
}
例子2:执行批量耗时操作,支持进度和取消
// Form1.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private BackgroundWorker backgroundWorker = null;
private void Button1_Click(object sender, EventArgs e) // 开始按钮
{
// 初始化 BackgroundWorker
if (backgroundWorker != null && backgroundWorker.IsBusy) return;
backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.WorkerSupportsCancellation = true;
backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
backgroundWorker.RunWorkerAsync(); // 可以传入参数
// 后续过程(不会被 BackgroundWorker 阻塞,即不会等待其完毕再执行)
// ...
}
private void Button2_Click(object sender, EventArgs e) // 取消按钮
{
if (backgroundWorker == null) return;
if (backgroundWorker.IsBusy && !backgroundWorker.CancellationPending) // 申请取消
{
backgroundWorker.CancelAsync();
}
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
//e.Argument // 可以取得传入的参数
// 模拟批量操作
for (int i = 0; i < 100; i++)
{
// 检查是否有取消申请
if (backgroundWorker.CancellationPending)
{
e.Cancel = true;
return;
}
// 模拟耗时操作
System.Threading.Thread.Sleep(50);
// 反馈进度
backgroundWorker.ReportProgress(i + 1);
}
string result = "...";
// 传递结果
e.Result = result;
}
private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
textBox1.Text = $"正在运行:{
e.ProgressPercentage}/100"; // 输出进度
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
textBox1.Text = (!e.Cancelled) ? $"运行结果:{
e.Result}" : "已取消"; // 输出结果
// 释放 BackgroundWorker
backgroundWorker.Dispose();
backgroundWorker = null;
}
}