GC calls finalizers, not Dispose. And the way GC works, there is no
guarantee when it will do it.
GC might not even fire after a long time, so the unmanaged resources remain
there for a long time.
This is why there is a need for an explicit release of unmanaged resources,
called dispose pattern,
embodied by the Dispose method.
WinForms runtime does call Dispose, when the form is closed (expect some
cases for MDI applications)
for all the controls it has, so you do not need to call Dispose explicitly.
If you do control.Icon=LoadFromFile() you create a new Icon object that is
holding a OS handle in it.
If you repeate the instruction, you in effect, create a new object with OS
handle in it but you leave the previous
object 'hanging' around. The previous object is could be marked unreacheable
so it will be collected someday, and finalized
someday+later. And it's only on someday+later that the OS handle will be
released.
You is why should call Control.Icon.Dispose() before assigning the new icon
for it (if it's not null).
This way you release the object and it's handle immediatly.
Whenever feasible, Dispose correctly (=explicitly and early). It helps to
keep the environment clean.
Laura
"PromisedOyster" <Pr************@hotmail.com> ha scritto nel messaggio
news:11**********************@j33g2000cwa.googlegr oups.com...
There are various contradictory newsgroup postings on this issue, but I
would really like a definitive answer from the .NET gurus out there?
We have various WinForms that contain multiple Icons and Bitmaps that
are loaded onto the form dynamically, eg control.Icon = ;. Should we
explicitly Dispose of these unmanaged resources when the form closes OR
should we leave it up to the garbage collector to remove these (and
will it definitively remove them?).
Currently, we are NOT disposing of them. However, we are experiencing
intermittent GDI errors, eg A generic error occurred in GDI+,
particularly on terminal server environments AND the GDI count (and
memory usage) grows as the user uses the system, but does not reduce
when the user closes the forms, despite forcing a call to
System.GC.Collect() when closing the form. Perhaps these issues are not
even related?
My understanding was that the recommended way was to let the garbage
collector sort things out, but I am now starting to wonder if this is
correct with applications that use a lot of unmanaged resources.