views:

40

answers:

1

Hi all,

I have a thread changes in a control in a form in a windows forms application,

I implement the invoke method for prevent threading cross access,

but when I close the form, the second thread still work and try to access to the control and throw an object reference not set to an instance of object exception

how can I assure preventing second thread working if the first one is not alive

without manual checking recommended

thanks in advance

A: 

Prior to closing the form, you could notify the thread that it is about to be cancelled. For example, if you are using BackgroundWorker for your thread you could call the CancelAsync method.

Update

To support this when using the Thread class you can either call Abort - which is not recommended - or you could use a shared variable. Basically you can have a boolean isCancelled that the thread periodically checks - and if it is false the thread returns. Then you can set this boolean from the UI thread to signal the background thread to stop. You would also need to make sure you properly lock the boolean before accessing it from either thread.

There are other techniques you can use as well - if you post your thread code we could help you more with that.

Justin Ethier