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?
There is a scenario in which a user terminates the application, while it is
Share
This is the code executed when you call CancelAsync() on a BackgroundWorker
As you can see, they set the internal
cancellationPendingvariable to true after checking the value ofWorkerSupportsCancellation.So you need to set
WorkerSupportsCancellation = true;, when you exit from your app callbackGroundWorkerInstance.CancelAsync()and inside the DoWork or RunWorkerCompleted test the CancellationPending. If it’s true stop your process.