Changing MainForm doesn't update reference in ThreadContext
- .NET Core Version: 3.1.200
- Have you experienced this same bug with .NET Framework?:
Haven't triedYes
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:

Also, even if the reference in currentForm is fixed it's still referenced on the stack through LocalModalMessageLoop(Form form) call.
Do you have any thoughts on how it could be fixed?
@filipnavara If you've got a suggested fix for this please let us know.
It’s been quite a while since I looked into it. The original suggestion was to either update the reference in ThreadContext when Application.MainForm is set to new value, or to always query the value in Application.MainForm and drop the local reference.