Dispose GDI+ object

  • Thread starter Thread starter #Hai
  • Start date Start date
H

#Hai

Hi,
I know that in C#, destructor is a finalize method. This means that the
destructor is only called when the Garbage collector does it job. But the
the GC is always does it job when the memory is full. Is there any thing
wrong ?

If it is true, now we consider GDI object (such as Image, Graphics, Pen.
Brush or even Timer (not GDI object) ). After we use it we assign the object
to null:

Pen p = new Pen(Color.Red);
//....using pen here
p = null;

If the above code is in a loop (repeat about 1000 times), a 128MB memory is
,certainly ,not full but the resource will run out of its capacity (because
none of finalization methods are called and therefore, none of pen resources
are free). That problem is much more seriously if the resource is timer (we
have only a few timer).

However, the following code works smoothly in less than 1 second and there
is no error reported by Windows
Graphics g = CreateGraphics();
for (int i= 0; i < 1000; i++)
{
Timer t = new Timer();
t.Interval = 100;
t.Start();
t.Stop();
}

Where is my mistakes ? Can any one point it ?
Thanks
 
Hi Hai -

Hmmm, not a C-sharpe' but maybe some ideas...

1) Use Dispose when it is available ( such as: p->Dispose() ) then
do
the p = null; Give it a try, & let us know. Read topics on
Dispose
and how it should be implemented for objects that use
unmanaged
stuff, and utilized to immediately free resources, such as
file handles.

2) I think declaring Timer t in the loop the way you have will
force a
Dispose on the previous t, without delay, as it wants to
replace it
immediately??

To my thinking, .NET has really obfuscated what I used to explicitly
manage,
and could trust. .NET seems to perpetuate the philosophy of
"sometimes you
need to, and sometimes you don't", and "sometimes it happens, and
sometimes
it doesn't" rather than trying to make hard rules. Now it is much
easier to not do something in some cases, and the casual read doesn't
make
it stand out. I'm not sure the code I make with it is more reliable or
faster.
Managed C++ is not C++ any more!

- HTH... Lee
 
Hi,

In addition to previous posts see also nice C# "using" statement, it
automatically generates Dispose call.

...
Regards,
Vadim.
 
Back
Top