winforms icon indicating copy to clipboard operation
winforms copied to clipboard

Changing MainForm doesn't update reference in ThreadContext

Open filipnavara opened this issue 5 years ago • 4 comments

  • .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

image

filipnavara avatar May 11 '20 23:05 filipnavara

Also, even if the reference in currentForm is fixed it's still referenced on the stack through LocalModalMessageLoop(Form form) call.

filipnavara avatar May 12 '20 20:05 filipnavara

Do you have any thoughts on how it could be fixed?

RussKie avatar May 22 '20 00:05 RussKie

@filipnavara If you've got a suggested fix for this please let us know.

JeremyKuhne avatar Jul 24 '24 21:07 JeremyKuhne

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.

filipnavara avatar Jul 24 '24 21:07 filipnavara