0

On some client machines I'm getting this System.ComponentModel.Win32Exception: The operation completed successfully error which apparently indicates resource leakage or hitting the hard limit of 10000 handles per process.

I'm looking through the code to refactor it and the pattern I'm using to create the windows is (simplified)

class MyForm : Form
{
  public MyForm()
  {
    InitializeComponents()
  }

  //windows generated code
  public void InitializeComponents()
  {
      myButton = new System.Windows.Forms.Button();
      myButton.Click += new System.EventHandler(myButton1_Click);
  }

  private void button1_Click(object sender, EventArgs e)
  {
      Dispose();
  }
}

//this will be called many times throughout the programs lifecycle
Form myForm = new Form()
myForm.ShowDialog();

Is reconstructing the Button each time the window is shown (there are numerous components in reality) likely to cause an issue with handles? I thought that dispose would have meant no but I'm struggling to find other code sections that could be causing the issue.

Community
  • 1
  • 1
probably at the beach
  • 14,489
  • 16
  • 75
  • 116

2 Answers2

2

You have to unsubscribe any subscriptions otherwise it pins the instance, never to be garbage collected because the subscription(s) is/are still active.

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
  • thanks for the answer. My understanding was this is only an issue when they were scoped differently (i.e the publisher might hold onto the subscriber after it was disposed if it hadn't been unsubscribed). – probably at the beach Nov 07 '13 at 00:40
  • @richarddruce One is only burned once by subscriptions and they never forget. :-) – ΩmegaMan Nov 07 '13 at 00:53
1

You should be calling Close() on the form, instead of Dispose, if you are not showing it as a modal form. Close will take care of closing the form and then dispose it automatically if it was not a modal form. If the form was modal, you should still call Close(), but then also call Dispose() afterward.

You should ALWAYS call Close() on a form that you are finished with, as there are a lot of Win32 calls that you'll be skipping, otherwise, that are a normal part of a windows forms application's lifecycle.

dodexahedron
  • 4,584
  • 1
  • 25
  • 37