c# - 以表单形式处置非托管资源

标签 c# winforms

我正在使用 Dispose 进行研发。我对 Forms 处理图像资源有疑问。

namespace DisposeTry
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Image mimg = new Bitmap("repository.png"))
            image1.Image = mimg;
        }
    }
}

由于显而易见的原因,我无法使用 mimg.Dispose 或将其包含在“using”中。何时以及如何处置此资源。请指教。

最佳答案

是的,你是对的,你需要手动处置 Bitmap 对象。

The .NET Bitmap class "encapsulates a GDI+ bitmap", that means you should call Dispose on a Bitmap when you are finished with it,

Always call Dispose before you release your last reference to the Image. Otherwise, the resources it is using will not be freed until the garbage collector calls the Image object's Finalize method.

您只需重写 Dispose 方法即可实现此目的。
然而,WinForms 的问题是你的表单是一个分部类,并且有一个部分 YourForm.Designer.cs,它是由 Visual Studio 自动生成的,并且已经实现了 Dispose处理WinForms组件的方法。
您需要将此方法移至您的代码中,请参阅this SO question了解更多信息。 .

然后,你的方法将如下所示:

protected override void Dispose(bool disposing)
{
  if (disposing)
  {
    if (components != null)
    {
      components.Dispose();
    }

    mimg.Dispose(); // mimg should be global, of course
  }

  base.Dispose(disposing);
}

关于c# - 以表单形式处置非托管资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38803241/

相关文章:

C#:Dictionary 的 [string] 索引器返回什么?

c# - 无法识别某些 C# 语法以转换为 VB.NET

c# - 多个类和表单的样式/架构健全性检查

winforms - 从最小化恢复 WindowState

c# - 关于平台游戏 Actor /背景碰撞解决的意见

java - 为什么 Java 只接受具有相同返回类型的重写基类方法?

c# - 委托(delegate)程序代码中的问题

c# - Winforms - 单击控件的 WM_NCHITEST 消息

c# - 如何将表单添加到控制台应用程序以便用户可以选择文件?

c# - MonthCalendar 没有点击事件?