Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unlockbits, lockbits, and try-finally

Tags:

c#

.net

I'm calling some code that uses the BitmapData class from .NET. I've hit something where I can't find a definitive answer on Googlespace.

Because it seems that LockBits and UnlockBits must always be called in a pair, I'm using this:

         System.Drawing.Imaging.BitmapData tempImageData = tempImage.LockBits(
            new System.Drawing.Rectangle(0, 0, tempImage.Width, tempImage.Height),
            System.Drawing.Imaging.ImageLockMode.ReadOnly, tempImage.PixelFormat);
         try
         {
            //use external library on the data
         }//Exception not handled here; throw to calling method
         finally
         {
            tempImage.UnlockBits(tempImageData);
         }

(I've recently been playing around with the using statement, which is very useful in C#, which gave me the idea that I should do this.) Trouble is, even MS's own documentation (http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.unlockbits.aspx) doesn't see it fit to use the try-finally pattern.

Is try-finally necessary or gratuitous?

Update: I may end up catching and rethrowing the exception, since I don't know what it might be and wasn't catching them earlier.

Thanks!

like image 313
Chris Avatar asked Sep 25 '08 15:09

Chris


2 Answers

The try-finally pattern is correct. Since this is external code, you have no control over what exceptions are thrown, and the UnlockBits cleanup code needs to be executed regardless of what error has occurred.

like image 140
Tron Avatar answered Oct 20 '22 00:10

Tron


Even if you do catch the exception, using finally means you don't duplicate the UnlockBits call, which is a plus in my option.

like image 27
Matt Avatar answered Oct 20 '22 00:10

Matt