[Gtk-sharp-list] widget destruction

Nicholas Frechette zeno490 at gmail.com
Wed Mar 9 10:54:13 EST 2011


On Wed, Mar 9, 2011 at 6:39 AM, Lluis Sanchez Gual
<slluis.devel at gmail.com>wrote:

> Subclasses may need to free their own unmanaged resources, which may not
> be related to gtk at all. For example, I could implement a widget
> subclass which pinvokes a C api to get some data, which has to be
> explicitly freed. I would free that data in the finalizer, but since the
> finalizer will not be called if the object is explicitly disposed, I
> also have to free that data in the Dispose method. So, I will end having
> a DeleteMyData method which is called from the finalizer and from
> Dispose.
>
> The Dispose pattern provides an standard solution to the above scenario.
> It states the need for a Dispose(bool disposing) method, to be called
> from Dispose and from the finalizer. The 'disposing' parameter is 'true'
> when calling from Dispose, meaning that it is safe to access other
> reference objects, and it is 'false' when called from the finalizer,
> meaning that only unmanaged data should be accessed.
>
> There is some documentation about this pattern here:
>
> http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx
>
>
I disagree strongly with the implicit destruction of managed resources
through the use of that pattern and the finalizer. Having worked extensively
on embedded systems where tight control over memory is always required, in
my experience, it is always better to provide tools for programmers to fix
bad usage than it is to brush it under the rug and do their job for them.
The finalizer should be there only to warn that memory is leaking and if you
must, free that memory, but the warning is key so that the code can be
fixed. Finalizers add a cost that can be very hard to measure.
All objects that have managed resources to discard should implement Dispose
and call base. Destroy should probably call Dispose (and not the other way
around). Either way, documentation has to state clearly which is which and
how to properly subclass widgets/other things.
Nicholas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.ximian.com/pipermail/gtk-sharp-list/attachments/20110309/b70f48fc/attachment.html 


More information about the Gtk-sharp-list mailing list