Stop Disposing of an Object Which Inherits From a Control

C

Chris Theorin

Anyone know how to do this? I tried this:
protected override void Dispose(bool disposing)

{

//base.Dispose (disposing);

if (!disposing)

base.Dispose(false);

}

But when something calls 'Dispose()' on this object of mine, like my objects
Parent Control (NOTE: base.Dispose(bool) is successfully avoided)... for
some reason references to my object start getting
System.ObjectDisposedException exceptions.
 
E

Elisa

Hi

The method base.Dispose(false) does not mean "Do not dispose this object"!

The parameter is used to differentiate between two differenct scenarios:

1. Dispose(true) is called explicitly (e.g. via your code)
2. Dispose(false) is called implicitly (e.g. via the garbage collector).

Examine the following code:

Public Overloads Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub

Protected Overrides Sub Finalize()
Dispose(False)
End Sub

Protected Overridable Overloads Sub Dispose(ByVal disposing As Boolean)
If disposing Then
' clean up managed resources
End If
' clean up unmanaged resources
End Sub

To prevent an Object from being disposed, you could try calling
GC.SuppressFinalize(MyObject). But it seems a rather weird scenario.
It's not uncommon that you want to explicitly dispose of an object, but
trying to PREVENT an object from being disposed usually indicates
something deeper is wrong.


Regards,

Elisa
 
C

Chris Theorin

I have a application-wide Popup Window that I add to the various Forms
throughout my application. If my Popup Window hasn't timed out by the time
the user wishes to close the form, my forms call dispose on all of their
children controls in their Dispose methods.

I'm pretty understanding of disposing (thanks for this nice summary though).
I added the base.Dispose(false) case only when false was passed into the
overriden Dispose(bool) method because this would mean that no one has a
reference to the object anymore (being garbage collected)... so I'm not
using it and I might as well pass this Dispose back to the base.

I'll probably just make my Popup Window function(s) handle creating a new
Popup Window multiple times throughout the application if necessary instead
of worrying about making sure this control doesn't get disposed and
SuppressFinalize and all that jazz...

Thanks!
 
E

Elisa

Hi Chris,

You might want to look into the Singleton pattern. This way, you will
only ever have one Popup Window object, and it will be automatically
disposed when the application finishes.


Regards,

Elisa
 
C

Chris Theorin

Do you know any samples showing usage of Singleton object in the compact
framework?
 

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