我有一个使用BackgroundWorker
组件的示例WinForms应用程序。它工作正常,但是当我点击Cancel
按钮取消后台线程时,它不会取消线程。当我点击Cancel
按钮调用.CancelAsync()
方法时,RunWorkerCompleted
事件处理程序e.Cancelled
属性始终保持为false
。我想当我点击Cancel
按钮时,它应该设置为true。
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
// Wait 100 milliseconds.
Thread.Sleep(100);
// Report progress.
if (backgroundWorker1.CancellationPending == true)
{
//label1.Text = "Cancelled by user.";
break;
}
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Change the value of the ProgressBar to the BackgroundWorker progress.
progressBar1.Value = e.ProgressPercentage;
// Set the text.
label1.Text = e.ProgressPercentage.ToString();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
label1.Text = "Canceled!";
}
else if (e.Error != null)
{
label1.Text = "Error: " + e.Error.Message;
}
else
{
label1.Text = "Done!";
}
}
private void button2_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
// Cancel the asynchronous operation.
backgroundWorker1.CancelAsync();
}
}
答案 0 :(得分:7)
Canceled属性仍然是false,因为你突破了循环,然后允许backgroundworker的DoWork函数以正常方式结束。您永远不会告诉您的后台工作组件实际上已接受待处理的取消。
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
// Wait 100 milliseconds.
Thread.Sleep(100);
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
break;
}
// Report progress.
backgroundWorker1.ReportProgress(i);
}
}
区别很重要,因为有时您可能需要在检测到CancellationPending请求时已经完成的回滚工作,因此在您实际完成取消之前可能需要一段时间。