Few things that can create memory leaks are:
- If you have a UserControl which you add dynamically to your form and if you attach events dynamically to this UserControl using:< br />
ucMyControl.btnSave.Click += new EventHandler(btnSave_Click);
and if you are removing you UserControl from the form using Controls.Clear() method then you must first remove all attached events before removing your UserControl using
ucMyControl.btnSave.Click -= new EventHandler(btnSave_Click);
- When removing dynamically added control from Form/Panel calling Controls.Clear() is not enough and instance stays in the heap after thar, so before this command call Dispose() on your dynamically added UserControl (that means that you should save a reference to your control in order to dispose it after)
-
If you have modal forms do not forget to call Dispose() after ShowDialog() method and set their reference to null in order to be garbage collected!
MyDialog dialog = new MyDialog(); dialog.ShowModal(); dialog.Dispose(); dialog = null;