BackgroundWorker.RunWorkerCompleted event in WPF

坚强是说给别人听的谎言 提交于 2019-12-25 03:08:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!