2

I am doing an R&D with Dispose. I have a doubt in case of Forms on disposing the image resource.

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;
        }
    }
}

I cannot use mimg.Dispose or enclose within 'using' for obvious reasons. The when and how to dispose this resource. please advise.

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
Priya
  • 77
  • 1
  • 12
  • I don't think you can do it explicitly, but the Garbage Collector will take care for it. In .NET when the objects go out of scope they're assigned to the Gabage Collector which will release they memory automaticlly. – Pau C Aug 06 '16 at 10:31
  • 1
    Just add a FormClosed event handler, call image1.Image.Dispose(). – Hans Passant Aug 06 '16 at 12:34

1 Answers1

4

Yes, you are right, you need to dispose Bitmap object manually.

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.

You can simply do this by overriding Dispose method.
However, the problem with WinForms is that your form is a partial class and there is a part YourForm.Designer.cs, which is automatically generated by Visual Studio and already implements Dispose method for disposing WinForms components.
You need to move this method to your code, read more in this SO question.

Then, your method will look like:

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

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

  base.Dispose(disposing);
}
Community
  • 1
  • 1
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
  • Note ; if you don't want the disposable item to be "global" and/or have multiple disposable to handle you can use a "global" `IList` and release them in a loop inside `Dispose` – Sehnsucht Aug 06 '16 at 10:45