"Cannot access a disposed object"

R

Rajat Tandon

Hi,

I have a grid which is continuously updating by the data from a external
event. When I close the form on which the grid is placed, then it gives the
error message ...

"Can not access a disposed object".

I understand that it is because as soon as the form is closed it will in
turn try to dispose the grid. I have unwired the event in the dispose of
grid (In which event I get the data) but it doesn't solve the purpose
completely. It is because when the dispose is called for grid, control might
be inside the method (Though I have already check in the start of the method
if the instance of the grid is not null) , where the grid is accessed.
Please tell me, how I can avoid this situation and dispose the grid
properly.

Regards,
Rajat.
 
G

Greg Young

I have seen a few causes of this ...

Are you by chance using invoke/begininvoke to move operations to the main
thread from a background thread? If you are you have a race condition .. The
background thread doing the updating looks and the grid is fine, its uses
begininvoke or invoke to send a message to the main thread to do the update.
Both invoke and begininvoke use PostMessage to put a message for the main
thread. While the message sits in the queue the datagrid is disposed. The
main thread then picks up the message from the queue and tries to execute
it. If this is your problem you can work around it by doing the check on the
main thread as opposed to in thge background thread
be inside the method (Though I have already check in the start of the
method
if the instance of the grid is not null) , where the grid is accessed.

Also you say that you are checking that the reference is not null .. the
reference is not null but is pointing to a disposed object (its still a
valid reference and is not null, it has just been told to release anything
internal and is therefore inaccessible)

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top