WPF中的BackgroundWorker.RunWorkerCompleted事件 [英] BackgroundWorker.RunWorkerCompleted event in WPF
问题描述
在某些情况下,用户仍在通过BackgroundWorker处理数据时终止了该应用程序.我想向该方法发送取消或终止命令.我尝试调用CancelAsync()方法,但是它显然没有按我预期的方式工作,并且工作程序仍在继续处理.用什么好方法来通知BackgroundWorker,尤其是其RunWorkerCompleted方法停止处理?我必须使用状态变量吗?
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?
推荐答案
这是在BackgroundWorker上调用CancelAsync()时执行的代码
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;
}
如您所见,他们在检查了 WorkerSupportsCancellation
的值之后,将内部 cancellationPending
变量设置为true.
As you can see, they set the internal cancellationPending
variable to true after checking the value of WorkerSupportsCancellation
.
因此,当您退出应用程序调用 backGroundWorkerInstance.CancelAsync()
并在DoWork或RunWorkerCompleted内部测试时,您需要设置 WorkerSupportsCancellation = true;
.如果是这样,请停止您的过程.
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.
这篇关于WPF中的BackgroundWorker.RunWorkerCompleted事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!