-->

How do I extend a WinForm's Dispose method?

2019-01-13 23:35发布

问题:

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?

回答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);
}


回答2:

I use this method :)

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


回答3:

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


回答4:

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