I am creating a WPF GUI application in vb.net that needs to interact with a COM API to perform some processor intensive work. Initially, I placed the work in a BackgroudWorker:
worker = New BackgroundWorker()
AddHandler worker.DoWork, AddressOf tsm.SAP_DoWork
AddHandler worker.ProgressChanged, AddressOf tsm.SAP_ProgessChanged
AddHandler worker.RunWorkerCompleted, AddressOf tsm.SAP_Completed
worker.RunWorkerAsync()
The tsm object has a reference to the mainWindow which is updated in the ProgressChanged handler. This works perfectly, except for one thing: I need to be able to abort the SAP_DoWOrk function instantly if the user clicks an abort button.
Now from my understanding of the cooperative cancellation model of the BackgroundWorker, this would mean enabling cancellation:
worker.WorkerSupportsCancellation = True
And then checking for this flag in the SAP_DoWork function. The problem is that this function calls many seperate processor intensive functions in several subclasses and also has a significant amount of logic, and I wish for the thread to stop immediately when cancelled.. So now it appears that I have two options:
- Place a check for cancellation before every action and abort the thread all the way up the call stack. This would mean the subclasses would also need to know about the cancellation and seems like an awful way of doing this.
- Abondon the BackgroundWorker way of doing things and find some functionality that supports killing threads safely. The data and progress of the background work does not need to be saved, as long as it doesn't affect the main thread.
I really don't want to do 1, so is there a way of doing 2 in VB.NET WPF applications? Is there some fundamental misunderstanding I have of how the BackgroundWorker works?