System.ObjectDisposedException: Cannot access a disposed obj

Posted by jmls on 29-Jan-2009 06:31

me again

Came across this today.

create a .net form, new it. Store the object in a variable

myfoo = new foo().

show the form

myfoo:Show()

user now closes the form by pressing the close button

check status of myfoo, if not valid then start the form again

if not valid-object(myfoo) then myfoo = new foo()

show form again

myfoo:Show()

then we get the error

System.ObjectDisposedException: Cannot access a disposed object

how do I get around this ?

All Replies

Posted by jmls on 29-Jan-2009 06:52

to answer my own question,

if not valid-object(myfoo) or myfoo:IsDisposed then myfoo = new foo()

works.

However, is this the right way (TM) ?

fixed typo

Message was edited by:

Julian Lyndon-Smith

Posted by Laura Stern on 29-Jan-2009 16:30

Yes - checking VALID-OBJECT and calling IsDisposed is the correct thing to do. When a form is closed, .NET automatically calls Dispose() on it. However the object is still there. Its destructor has NOT run. And in this case, the ABL still has a valid object reference to the form instance. However, as you found out, once it is disposed, the form is no longer useable. So checking IsDisposed is the way to find out if you can still use it.

Posted by jmls on 29-Jan-2009 16:38

Thanks Laura for the clarification. Just out of interest, why isn't the object destroyed, and when does the destructor get run ?

I also saw that all properties of the object were accessible. I presume that this is expected behaviour as well.

Posted by Admin on 29-Jan-2009 23:30

All used ressources (like the Controls on the Form) have already been released while Disposing the Form. But you still can query properties like DialogResult (may be important for a caller), Size and Location (to save position and size for next run).

The Form will actually get Destroyed by the GC, when no reference to it exists anymore (setting the Variable to ? is a good start).

Posted by rbf on 02-Feb-2009 03:53

So when I start a Dialog I can safely query any property from the caller after the Dialog is closed?

This thread is closed