问题
I have this:
Bitmap bmp = new Bitmap(image);
//image processing
bmp.Save(path + fileName);
and I want to know if I need to call bmp.Dispose()
after this code.
Thanks in advance.
回答1:
I would use using
block and Path.Combine
using(var bmp = new Bitmap(image))
{
// image processing
bmp.Save(Path.Combine(path ,fileName));
}
回答2:
Yes.
Better yet, you could wrap your bmp in a using block, this will take care of the disposal for you
using(var bmp = new Bitmap(image))
{
bmp.Save(...);
}
Save's sole purpose is to save the image to the specified file, it doesn't change the bitmap object
回答3:
There's a simple rule: if you've created a disposable instance and haven't passed it to another ower, you should dispose it. In your code; since you've created Bitmap you're supposed to dispose it as well:
using (Bitmap bmp = new Bitmap(image)) { // <- Creation
// Image processing
...
bmp.Save(path + fileName);
} // <- You no longer need the bitmap, let's dispose it
回答4:
If you're done with it: yes. Based simply on the fact that
- it implements
IDisposable
, and - you're done with it
To be honest, those two points are essentially the entire debate - everything else is implementation details. Although in this case the implementation details are probably GDI+ handles, which are definitely worth cleaning up properly. But you can make your life easier with using
:
using(var bmp = new Bitmap(image))
{
// image processing
bmp.Save(path + fileName);
}
回答5:
Yes, you need to call Dispose()
method, otherwise bitmap recources being in use before garbage collertor calls finalizer method.
Just use the using
operator:
using(var bmp = new Bitmap(image))
{
// image processing
bmp.Save(path + fileName);
}
来源:https://stackoverflow.com/questions/18119719/c-dispose-a-bitmap-object-after-call-bitmap-save