Control can't be properly GC-collected after disposing because of it referenced via the System.Windows.Forms.Control.cachedLayoutEventArgs field
See original GitHub issueThe same bug is reproducible with .NET Framework but it seems it has no chance to be ever fixed. But the .NET Core looks like a good place for introducing some improvements in this area.
Problem description
Each instance of the System.Windows.Forms.Control
type contains a private member variable of the LayoutEventArgs
type - cachedLayoutEventArgs . And, the LayoutEventArgs
instance typically contains a reference to some specific control.
Sometimes, the cachedLayoutEventArgs
field is not cleared when the child control disposing of does not affect the layout process of the parent control due to some reasons.
Reproduction
Here are the minimal reproduction-steps:
- Create a form with two buttons.
- Add the following code for the corresponding
Button.Click
handlers:
void btnOpenView_Click(object sender, System.EventArgs e) {
var view = new Panel() { BackColor = Color.Red };
view.Name = "View";
view.Bounds = new Rectangle(100, 100, 100, 100);
view.Parent = this;
}
void btnCloseView_Click(object sender, System.EventArgs e) {
SuspendLayout();
var view = this.Controls.Find("View", false)[0];
if(view != null)
view.Dispose();
ResumeLayout(false);
}
- Press the “Open View” button - red panel appears.
- Press the “Close View” button - red panel disappears.
Actual behavior:
The panel is still referencing via the System.Windows.Forms.Control.cachedLayoutEventArgs
field at the form level. As result, it can’t be GC-collected properly and still in memory.
Expected behavior: The panel should not be referenced.
Proposal for Fix
It looks like we should use the WeakReference
when caching the LayoutEventArgs
.
As an alternative solution, we can validate the cachedLayoutEventArgs
value on child control removing and clear the problematical field.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:16 (14 by maintainers)
Verified in the latest 8.0 SDK build: 8.0.100-rc.1.23375.11, it was fixed: there is no related panel leaks after GC-collected.
Sure. We should re-prioritize issues this week, anyway, but I am guessing, this will be waiting a little time longer.