- .NET Core Version: 3.1.200
- Have you experienced this same bug with .NET Framework?:
Haven't tried Yes
Problem description:
We have an application that can have more than one form open. When one of these forms is closed and it was the ApplicationContext.MainForm one we switch it to another opened window. Once all the windows are closed we shut down the app.
Currently the Application.ThreadContext class holds an additional reference to the main form that is assigned only at the beginning of the message loop. It doesn't reflect any changes to ApplicationContext.MainForm which is documented to be allowed:
/// <summary>
/// Determines the mainForm for this context. This may be changed
/// at anytime.
/// If OnMainFormClosed is not overriden, the thread's message
/// loop will be terminated when mainForm is closed.
/// </summary>
Changing MainForm doesn't update reference in ThreadContext and hence the memory for the old form is never released. Similarly, any properties that are checked in the ThreadContext class are checked on a wrong form.
Expected behavior:
ThreadContext should not hold its own reference to MainForm. If it needs it then it should be updated accordingly, either periodically in the loop, or through some mechanism from inside Application.MainForm setter.
Minimal repro:
MainFormLeak.cs.zip

Haven't triedYesProblem description:
We have an application that can have more than one form open. When one of these forms is closed and it was the
ApplicationContext.MainFormone we switch it to another opened window. Once all the windows are closed we shut down the app.Currently the
Application.ThreadContextclass holds an additional reference to the main form that is assigned only at the beginning of the message loop. It doesn't reflect any changes toApplicationContext.MainFormwhich is documented to be allowed:Changing MainForm doesn't update reference in ThreadContext and hence the memory for the old form is never released. Similarly, any properties that are checked in the ThreadContext class are checked on a wrong form.
Expected behavior:
ThreadContext should not hold its own reference to MainForm. If it needs it then it should be updated accordingly, either periodically in the loop, or through some mechanism from inside
Application.MainFormsetter.Minimal repro:
MainFormLeak.cs.zip