dotnet / dotnet/winforms

Changing MainForm doesn't update reference in ThreadContext

Open
#3,260 4 comments 0 reactions 1 assignee Claimed by @JeremyKuhne View on GitHub
:beetle: bug :construction: work in progress tenet-performance
Dominant language
C#
Stars
4.9k
Forks
1.1k
Avg merge
1d 13m
Merged PRs (30d)
85

Description

* .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:

```c#
///
/// 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.
///
```

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](https://github.com/dotnet/winforms/files/4612656/MainFormLeak.cs.zip)

![image](https://user-images.githubusercontent.com/1764393/81623212-398b7c00-93f3-11ea-9a35-6e83b0c6fc2a.png)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.