Skip to content

Control.Dispose crashes during finalization when Properties was not initialized #14393

@wjrogers

Description

@wjrogers

.NET version

10.0.200

Did it work in .NET Framework?

Yes

Did it work in any of the earlier releases of .NET Core or .NET 5+?

Yes, in .NET 9.0.

Issue description

Control.Dispose(bool disposing) can throw during finalization if/when the control's constructor threw TypeInitializationException because it de-references Properties when it is null. This issue was previously reported in #13835, but the fix was never merged to the .NET 10 release branch. Is it possible to port #13840 to release/10.0?

(I am unable to comment on the closed issue or its linked pull request because they are locked.)

Steps to reproduce

Run the below program and click the button twice.

#:property PublishAot=false
#:property UseWindowsForms=true
#:property TargetFramework=net10.0-windows

ApplicationConfiguration.Initialize();
Application.Run(new MainForm());

class MainForm : Form
{
    public MainForm()
    {
        Button button = new() { Text = "Click me", Dock = DockStyle.Fill };
        button.Click += (sender, e) =>
        {
            try
            {
                var borked = new BrokenControl();
            }
            catch { }
            GC.Collect();
            GC.WaitForPendingFinalizers();
        };
        this.Controls.Add(button);
    }
}

class BrokenControl : UserControl
{
    Foo bar = new();
}

class Foo
{
    static Foo()
    {
        throw new Exception("Fails");
    }
}

Metadata

Metadata

Assignees

Type

No fields configured for Bug.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions