我正在调用一些使用 .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);
}
(我最近一直在研究 using 语句,它在 C# 中非常有用,这让我想到我应该这样做。)问题是,即使是 MS 自己的文档(http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.unlockbits.aspx)也没有认为适合使用 try-finally 模式。
try-finally 是必要的还是不必要的?
更新:我可能最终捕获并重新抛出异常,因为我不知道它可能是什么并且没有更早地捕获它们。
谢谢!
最佳答案
try-finally 模式是正确的。由于这是外部代码,您无法控制抛出的异常,无论发生什么错误都需要执行 UnlockBits 清理代码。
关于c# - unlockbits、lockbits 和 try-finally,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/133958/