我几乎没有找到如何通过停止按钮取消Backgroundworker的好方法:
我的 App 看起来像这样,两个按钮和一个进度条:
按下停止按钮后,它看起来像这样:
对于 Start button click 方法,代码检查 BGW 是否忙。如果没有启动 BGW:
private void btnStart_Click(object sender, EventArgs e)
{
//BGW
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
}
停止按钮调用以下方法,该方法将标志CancellationPending设置为 true:
private void btnStop_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
这个标志可以在 backgroundWorker1 _DoWork方法中使用,该方法负责处理高耗时函数:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i <= 100; i++)
{
backgroundWorker1.ReportProgress(i);
Thread.Sleep(100);
if (backgroundWorker1.CancellationPending && backgroundWorker1.IsBusy)
{
e.Cancel = true;
return;
}
}
}
现在到了棘手的部分,因为在关闭额外线程之前,您必须检查backgroundWorker1 _ProgressChanged中的e对象是否被取消!!!!!!否则你会得到一个错误。
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
int i = 0;
if (!e.Cancelled)
{
i = (int)(e.Result);
}
else
{
i = 0;
}
// Check to see if an error occurred in the
// background process.
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
return;
}
// Check to see if the background process was cancelled.
if (e.Cancelled)
{
MessageBox.Show("Processing cancelled.");
return;
}
// Everything completed normally.
// process the response using e.Result
MessageBox.Show("Processing is complete.");
}
额外信息:
不要忘记设置这些 Backgroundworker 标志:
//Set WorkerReportsProgress true - otherwise no ProgressChanged active
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
如果这个小教程有帮助--> 点赞