简体   繁体   中英

Do I need to dispose of Bitmap instances used in a static method of a static class?

I am looking at a small Image Cropping and Resizing library written in C#. It consists of a single static class with static methods for resize and crop funcions.

For example the crop method:

public static Image Crop(Image img, Rectangle cropArea)
{
    var bmpImage = new Bitmap(img);
    var bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
    return bmpCrop;
}

I know that typically, Bitmap objects need to be disposed of to prevent memory leaks, but Is this a different case because of the class being static?

I dont want to implement this library and run into memory problems down the road

First, when using Bitmaps I would warn against using them from a static class if at any time you wish to use more than one thread. No bitmap can be used by more than one thread at a time. So for example if you next did this in one thread:

using(Graphics g = Graphics.FromImage(bmpCrop)
{
   // do something
}

and on another

int w = bmpCrop.Width

you will get an invalid parameter exception.

Next, in your example, I see three image instances...

  • img
  • bmpImage
  • bmpCrop

Right now you aren't disposing bmpImage in this function and would need to. After this call it would be the callers responsibility at some point to dispose of img and bmpCrop

Being static doesn't change the requirement for disposal (as a general rule). What you do have to consider is will the Bitmap be used after the static method has completed. So, for example, if you're returning the Bitmap out of your function then you don't want to dispose of it because you're anticipating that someone else (some other code) is going to need to use it, and so it becomes his responsibility to dispose of it.

But the mere fact that the method itself is static has no bearing, if you would have disposed of it in a non-static method, you should dispose of it in a static method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM