c#
BackgroundWorker使用介绍
用途:在单独的线程上执行任务,即在一个线程中执行一个fuction或者代码
使用
//创建BackgroundWorker对象
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerSupportsCancellation = true; //是否支持运行时取消操作
backgroundWorker.WorkerReportsProgress = true; //是否支持 报告执行进度
//注册事件
backgroundWorker.DoWork += backgroundWorker_DoWork; //开始执行任务事件,任务运行在线程中,不可在此线程中直接更新UI线程(如设置TextBox1.Text="123")
backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged; //报告执行进度事件,运行在UI线程,可直接更新UI,如设置TextBox1.Text="123",ProcessBar1.Value = value
backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;//任务执行完成事件,运行在UI线程,可直接更新UI,如设置TextBox1.Text="123", ProcessBar1.Value=100
//触发任务
private void btnRun_Click(object sender, EventArgs e)
{
string input_param = "file path";
// 向后台任务传参
if (backgroundWorker.IsBusy != true)
{
backgroundWorker.RunWorkerAsync(input_param);
}
}
//取消任务
private void btnRun_Click(object sender, EventArgs e)
{
if (backgroundWorker.WorkerSupportsCancellation == true)
{
backgroundWorker.CancelAsync();
}
}
// 后台执行的任务
private void backgroundWorker_DoWork(object? sender, DoWorkEventArgs e)
{
//后台任务接收传入的参数
string input_param = e.Argument.ToString();
//后台执行任务代码
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 10; i++)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
system.Threading.Thread.Sleep(500);
worker.ReportProgress(i * 10); //报告执行进度,触发ProgressChanged事件
}
}
}
//更新UI介面任务执行进度
//运行在UI线程
private void BackgroundWorker_ProgressChanged(object? sender, ProgressChangedEventArgs e)
{
//获取执行进度 int型 e.ProgressPercentage
this.progressBar1.Value = e.ProgressPercentage;
}
//后台任务执行完成事件处理程序
//运行UI线程
private void BackgroundWorker_RunWorkerCompleted(object? sender, RunWorkerCompletedEventArgs e)
{
this.progressBar1.Value = 100;
}