This is my code:
Bitmap bmp = ImageManipulator.GetMyImageModified(bmp);
Bitmap tempBMP = ImageManipulator.cropImage(bmp, rect);
tempBMP = ImageManipulator.CopyToBpp(tempBMP, 1);
string bmpFilename = String.Format("File{0}.png", indexNum);
tempBMP.Save(bmpFilename, ImageFormat.Png);
Now I’ve seen that for IDisposable objects is a best practice to use the using statement to dispose those object as soon as they are not needed anymore.
I want to follow this practise and so I need some help rewriting the above code:
using (Bitmap bmp = ImageManipulator.GetMyImageModified(bmp){
Bitmap tempBMP = ImageManipulator.cropImage(bmp, rect); // bmp should be disposed after this line
tempBMP = ImageManipulator.CopyToBpp(tempBMP, 1);
string bmpFilename = String.Format("File{0}.png", indexNum);
tempBMP.Save(bmpFilename, ImageFormat.Png);
} // bmp is disposed here
This is my first attempt but it’s not perfect cause the bmp Bitmap is non disposed as soon as not needed anymore though in this specific example shouldn’t be mandatory to get it disposed so fast.
tempBitmap is more problematic because i cannot reassign the reference to a new Object inside the using statement that should surrond:
Bitmap tempBMP = ImageManipulator.cropImage(bmp, rect);
Indeed tempBMP reference becomes readonly after surrounding the above line with the using keyword.
Also tempBMP gets saved to a file and the Save operation should be asyncrhonous and then I don’t know the effects of a dispose as soond as the:
tempBMP.Save(bmpFilename, ImageFormat.Png);
Get called.
If you can help me write better code, I’m all ears.
1 Answer