问题
There is a scenario in which a user terminates the application, while it is still processing data via BackgroundWorker. I would like to send cancel or terminate command to this method. I tried calling CancelAsync() method, but it obviously didn't work the way I expected and the worker still continued processing. What is a good way to signal the BackgroundWorker, and especially its RunWorkerCompleted method to stop processing? Do I have to use state variables?
回答1:
This is the code executed when you call CancelAsync() on a BackgroundWorker
public void CancelAsync()
{
if (!this.WorkerSupportsCancellation)
{
throw new InvalidOperationException(SR.GetString
("BackgroundWorker_WorkerDoesntSupportCancellation"));
}
this.cancellationPending = true;
}
As you can see, they set the internal cancellationPending
variable to true after checking the value of WorkerSupportsCancellation
.
So you need to set WorkerSupportsCancellation = true;
, when you exit from your app call backGroundWorkerInstance.CancelAsync()
and inside the DoWork or RunWorkerCompleted test the CancellationPending. If it's true stop your process.
来源:https://stackoverflow.com/questions/12222436/backgroundworker-runworkercompleted-event-in-wpf