Returning memory

  • Thread starter Thread starter victor
  • Start date Start date
V

victor

Hi,
I've the following question: in my app I used the following construct
to acquire images:

Image imgImage;
Stream myStream=null;
....
private void GetImageObject()
{
imgImage = new Bitmap(myStream);
picboxImageHolder.Image=imgImage;
....
}
--------------
The GetImage method is being invoked every second thru a timer tick.
This results in a cumulating memory consumption (seen in TaskManager).
Since 'delete' isn't available in C#, how should I return this memory?
Rely on GarbageCollector?
Please advise - thank you!
victor.
 
Victor,

That is exactly what you do. However, a Bitmap does use some unmanaged
resources (it implements IDisposable), so I would be concerned about leaving
those for the GC to clean up.

To do this, I would call dispose on the image that the image holder is
currently holding, before you assign the new bitmap to it, like so:

private void GetImageObject()
{
// Get the old image.
imgImage = picboxImageHolder.Image;

// Dispose.
imgImage.Dispose();

// Set the new bitmap.
picboxImageHolder.Image = new Bitmap(myStream);
}

However, I would use the using statement, like so:

using (Image oldImage = picboxImageHolder.Image)
{
// Set the new image.
picboxImageHolder.Image = new Bitmap(myStream):
}

This will set the image to the new image, and then dispose of the old
image (assuming there is one) when the new image is set.

It is also more concise.

Hope this helps.
 
Great, Nicholas; thanks for the response.
I'll implement it first thing tomorrow!
greetz, victor.
 
Nicholas,

Works perfectly - just what I need! ('used the using method)
Appreciate your answering manner: clear, immediately usable snippets.
Thank you for sharing your knowledge!
greetz, Victor
============
 
I would use the more verbous form.

The trick using "using" is neat, but it's still a trick. The construct
is only used to call dispose, it serves no other purpose. IMHO the code
gets clearer if it just calls dispose instead of causing the call as a
byproduct of an unused construct.
 
I, however, prefer "using". As long as the syntax is clear and snappy, why
not use it?

It's similar to "with" in Lisp, if I recall correctly.
 
I'm not against the use of "using" per se. I use it frequently myself.

I couldn't find anything about "with" in lisp. If it works like "with"
in other languages (VB, Pascal), it's nothing like "using".

The normal use of the "using" keyword is when you create an object that
you want to dispose when you are done with it. If it's used to dispose
an object that you don't create at that time, you have to understand
exactly what the entire piece of code is doing before you can see why
"using" is used at all.
 
Back
Top