How to stop the BackgroundWorker?

pisceswzh

Well-known member
Joined
Mar 19, 2007
Messages
96
Programming Experience
1-3
Hi,

In my application, I use the BackgroundWorker to load the data from the database.

I use the BackgroundWorker DoWork event to load the data from the database to a datatable and in the BackgroundWorker RunWorkerCompleted event to assign the datatable to the datasource property of a datagrid.

The problem is if the user close the form while the DoWork event is still in process and when the event is done, the RunWorkerCompleted starts and tries to assign the datatable to the datasource property of the datagrid which has been no longer existed (since the form has been closed).

Is there a way to stop all the BackgroundWorker when the form is closed or is there a better approach in my situation?

Thanks!
 
Call the BackgroundWorker's CancelAsync method in the FormClosing event handler. In the DoWork event handler assign the BackgroundWorker's CancellationPending property value to the e.Cancel property. In the RunWorkerCompleted event handler test the e.Cancel property and don't do anything if it's True.
 
No, that is not to say that at all. Just assign the BackgroundWorker object to a class level variable when you create. You could set the variable back to Nothing in the RunWorkerCompleted event handler if you wanted to.
 
You've also got the option of simply testing the form's IsDisposed property in the RunWorkerCompleted event handler and just not doing anything if it's True.

If you cancel the worker though, you have the option of not wasting processor time doing all the work if it's possible to opt out early.
 

Latest posts

Back
Top