Reputation: 15813
I have a user control with bitmaps that should be disposed when the form closes. Is it better to do this in the form's Closing event, Closed event, or somewhere else?
Part 2: Inside a user control, when its form closes, should a bitmap be disposed in the Disposed event or somewhere else?
Upvotes: 1
Views: 1200
Reputation: 941465
No, the form has no business messing with private members of the user control. The universal .NET rule applies here as well, a class needs to dispose its members in its own Dispose() method. It will run automatically when the form closes, no assistance is needed.
There's a quirk however, the project item template for UserControl is awkward. It puts the Dispose() method inside the control's Designer.cs file. Best thing to do is to cut+paste this method into the control's main source file. After you edited the method, it ought to resemble this:
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
someBitmap.Dispose(); // <== added
someOtherBitmap.Dispose();
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
Some programmers really dislike tinkering with the Designer.cs file, do note that there's nothing to worry about since the code is outside the #region marked Component Designer generated code
. The alternative is to use the Disposed event:
public UserControl1() {
InitializeComponent();
this.Disposed += UserControl1_Disposed;
}
void UserControl1_Disposed(object sender, EventArgs e) {
someBitmap.Dispose();
someOtherBitmap.Dispose();
}
Upvotes: 5