How do I extend a WinForm's Dispose method?

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?


Solution 1:

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:

I use this method :)

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