unlockbits,lockbits和try-finally

Chr*_*ris 5 .net c#

我正在调用一些使用.NET的BitmapData类的代码.我找到了一些我无法在Googlespace上找到明确答案的东西.

因为似乎必须始终在一对中调用LockBits和UnlockBits,所以我使用它:

         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);
         }
Run Code Online (Sandbox Code Playgroud)

(我最近一直在使用using语句,这在C#中非常有用,这让我觉得我应该这样做.)麻烦的是,即使是MS自己的文档(http://msdn.microsoft.com/ en-us/library/system.drawing.bitmap.unlockbits.aspx)认为它不适合使用try-finally模式.

尝试 - 最后是必要的还是无偿的?

更新:我可能最终会捕获并重新抛出异常,因为我不知道它可能是什么,并且没有提前捕获它们.

谢谢!

小智 7

try-finally模式是正确的.由于这是外部代码,因此您无法控制抛出的异常,并且无论发生了什么错误,都需要执行UnlockBits清理代码.