System.Drawing and Garbage Collection
As some may be aware, I recently posted about high memory usage on my website and I have an idea that my thumbnailer may have something to do with this as I am not actively disposing of the instance when it has been used due to my misunderstanding how it works.
I am now looking at my code for the thumbnailer and would like some advice on when开发者_开发知识库 something would actually need disposing of, is it ONLY when you create a new instance of an object?
Like:
Target := System.Drawing.Bitmap.Create(Trunc(Width), Trunc(Height));
MyImage := Target.FromFile(PhotoPath);
So, my question would be, do I need to dispose of both Target and MyImage to make sure the GC does what it needs to do properly?
Thanks.
Check out this blog post on MSDN: .NET Memory Leak: To dispose or not to dispose, that’s the 1 GB question. The recommendation appears to be that you should be disposing.
I would, as a general policy, turn the question on its head:
Is there any reason I should not disposed of these particular objects
If the class implements IDisposable
, it's your job to dispose of it.
In many cases though the object doesn't do much when you dispose of it, but that doesn't mean you shouldn't call Dispose on it. If you ever upgrade to a new .NET runtime version, that might've changed.
Ok, let me clarify what I said here.
Of course I'm not saying you should just call Dispose
on any and all objects that implement IDisposable
. The question is, is it your object. If you constructed it, it is your responsibility.
If you were given the object, assume it isn't yours, unless you specifically require the object to be given, and not just loaned out to you temporarily.
And of course there are other exceptions as well, but as a general rule, objects you own that implement IDisposable
, dispose of them when you're done.
Image
implements disposable. You should dispose it when you're done with it. With images it is very important to dispose them. They allocate just a few bytes of managed memory, but reference a large block of native memory.
Yes, both calls result in the creation of new Bitmap
objects, so you need to dispose them when you are done with them.
You should also be aware that there are other graphics related objects that you might be using that also needs to be disposed, like Graphics
, Brush
and Font
.
Yes, Dispose the IDisposables you have created. Certainly in the GDI+
Preferably in a using() {}
block.
using (Pen p = new Pen(Colors.Blue)) // Dispose this pen
{
Brush b = Brushes.Green; // but not this Brush
....
}
精彩评论