How to detect resource leaks in a Form | |||
| |||
1. Run the Windows Task Manager 2. Select the Processes tab. 3. Select the View / Select Columns menu item. 4. Check the User Objects and GDI Objects checkboxes. 5. In the code that launches the Form, make sure you call the Dispose method (Forms implement the IDisposable interface so their Dispose method must be called the moment they're no longer needed). You can call Dispose explicitly (see Example 1, below), or, better still, instantiate the Form in a using block (Example 2). 6. For troubleshooting purposes only, insert a call to GC.Collect() after the using statement, or after the call to Dispose(). 7. Launch the Form and close it a few times. Then, when the Form is closed, note the Task Manager's User Objects and GDI object values. Launch and close the Form. If the User Objects and/or GDI objects have increased, there is a leak in the Form. 8. Fix the resource leak, and remove the call to GC.Collect(). It's generally unnecessary to make an explicit call to GC.Collect(). Example 1: // Explicit call to Dispose: AboutForm aboutForm = new AboutForm(): aboutForm.ShowDialog(); aboutForm.Dispose(); // Force garbage collection. GC.Collect(); Example 2: // Implicit call to Dispose (the using statement causes // Dispose to be called immediately after the using block, // when the form goes out of scope. using (AboutForm aboutForm = new AboutForm()) { aboutForm.ShowDialog(); } // Force garbage collection. GC.Collect(); I have found at least two ways to leak memory and/or resources in a Form: 1. Include a MainMenu in the Form. 2. Add an EventHandler to the Application.Idle event that calls one of the Form's methods. You can fix this by simply removing the EventHandler from the Application.Idle event when the Form is closing (use the -= operator). Tags: Append C# | |||
| |||
| |||
Login for comment |