How do I extend a WinForm's Dispose method?

C#WinformsDisposeFxcop

C# Problem Overview


I am getting this warning from FxCop:

> "'RestartForm' contains field 'RestartForm.done' that is of IDisposable type: 'ManualResetEvent'. Change the Dispose method on 'RestartForm' to call Dispose or Close on this field."

Ok, I understand what this means and why this is what needs to be done... Except System.Windows.Forms.Form doesn't allow you to override either .Close() or .Dispose(), so what to do? Currently I'm running with this solution:

    private void RestartForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        done.Set();
        done.Close();
    }

Which works as intended for my application... But FxCop still shows this message. Am I covered and can I safely ignore it, or is there another way I should be doing this?

C# Solutions


Solution 1 - C#

You need to override the Dispose method from Form

Typically this is automatically overridden in the RestartForm.Designer.cs file, so you will need to move the dispose into your code file so that you can add whatever code you need to add without it being rewritten by the designer.

In the RestartForm.cs

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

    // Dispose stuff here
  }

  base.Dispose(disposing);
}

Solution 2 - C#

I use this method :)

            Image bgImage = Image.FromFile(workingDir + "\\" + button.BackgroundImage);
            currentButton.Image = bgImage;
            currentButton.Disposed += (Object sndr, EventArgs evnt) => bgImage.Dispose();

Solution 3 - C#

If RestartForm extends System.Windows.Forms.Form, you should be able to override Dispose(bool disposing). You should properly implement this for your "RestartForm" class to dispose of your IDisposables.

It should look like:

public override Dispose(bool disposing)
{
   if (disposing)
   {
       // Dispose was called from user code. Dispose of managed resources here.
       done.Dispose();
   }
 
   // Dispose of unmanaged resources here, and invoke base dispose.
   base.Dispose(disposing);
}

Solution 4 - C#

You need to override the Dispose method, this method comes from the Control base class

protected override void Dispose(bool disposing)
{
  if (disposing)
  {
    event.Dispose();
  }
  base.Dispose(disposing);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatthew ScharleyView Question on Stackoverflow
Solution 1 - C#heavydView Answer on Stackoverflow
Solution 2 - C#AlexTheoView Answer on Stackoverflow
Solution 3 - C#wompView Answer on Stackoverflow
Solution 4 - C#Shay ErlichmenView Answer on Stackoverflow