我很难找到一个很好的方式如何取消一个BackgroundWorker的在停止按钮:
我的应用程序是这样的,两个按钮和一个进度:
按下停止按钮后,它看起来像这样:
对于开始按钮点击方法,代码检查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;
}
}
}
现在出现了棘手的部分,因为在关闭额外的线程之前,如果它被取消或不被取消,你必须检查后台对象中的对象012!否则你会得到一个错误。
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;
如果这个小教程是有帮助 - >赞许
你是在等'RunWorkerCompleted'事件用于启动*开始处理*按钮? –
“我这样做,以便在每次循环迭代时,它检查取消挂起是否为真,如果是,则打开循环。”当取消挂起为真时,您是否将DoWorkEventArgs e parametrs Cancel属性设置为true? => e.Cancel = true; – boli