c# - unlockbits、lockbits 和 try-finally

标签 c# .net

我正在调用一些使用 .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/

相关文章:

c# - 为什么以下数组不写入文件?

c# - VS WPF设计器: how to add control from referenced project to a form in the main project

.net - 项目什么时候需要 Azure?

.net - WCF 服务连接问题 - 也许安全?

.net - 请求的性能计数器不是自定义计数器,它必须初始化为只读

c# - 如何从解决方案中获取 64 位 exe 文件?

c# - 自动更新 Windows 10 IoT 核心版内的应用程序?

c# - 我不太明白 MySql 连接是什么样的

.net - 无法加载文件或程序集 - 该模块应包含程序集 list

.net - 两个应用程序同时使用 SQL Server Compact 版本