我在WPF应用程序中有一个BackgroundWorker
。如果条件为真,我想立即停止处理_DoWork
方法并直接转到_RunWorkerCompleted
。我正在使用.CancelAsync
,但此后的代码继续执行。
如何取消_DoWork
并进入_RunWorkerCompleted
?
示例:
private BackgroundWorker step1 = new BackgroundWorker();
public MyWindow()
{
InitializeComponent();
step1.WorkerSupportsCancellation = true;
step1.DoWork += new DoWorkEventHandler(step1_DoWork);
step1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(step1_RunWorkerCompleted);
}
private void step1_DoWork(object sender, DoWorkEventArgs e)
{
if (someCondition)
{
step1.CancelAsync();
}
// code I do not want to execute
}
private void step1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// I want to jump here from the cancel point
}
答案 0 :(得分:2)
CancelAsync
是一种方法,旨在由除DoWork
处理程序之外的调用,以指示DoWork
处理程序应该停止执行。 DoWork
处理程序应该检查BGW是否请求取消,如果是,则停止执行(通过返回,抛出异常或者不执行进一步的工作)。
答案 1 :(得分:1)
在DoWork
处理程序中,检查取消状态。
private void step1_DoWork(object sender, DoWorkEventArgs e)
{
if (someCondition)
{
step1.CancelAsync();
}
if (!step1.CancellationPending)
{
// code I do not want to execute
}
else
{
e.Cancel = true;
return;
}
}
答案 2 :(得分:1)
private void startAsyncButton_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy != true)
{
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync();
}
}
private void cancelAsyncButton_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
// Cancel the asynchronous operation.
backgroundWorker1.CancelAsync();
}
}
// This event handler is where the time-consuming work is done.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
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);
}
}
}
// This event handler updates the progress.
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
resultLabel.Text = (e.ProgressPercentage.ToString() + "%");
}
// This event handler deals with the results of the background operation.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
resultLabel.Text = "Canceled!";
}
else if (e.Error != null)
{
resultLabel.Text = "Error: " + e.Error.Message;
}
else
{
resultLabel.Text = "Done!";
}
}
}
}