Handles keep increasing when repeatedly showing/closing a Window on a separate Dispatcher thread
- Dominant language
- C#
- Stars
- 7.7k
- Forks
- 1.3k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 61
Description
### Description
In a WPF application, when starting a dedicated STA thread running Dispatcher.Run() and repeatedly creating, showing, and closing a Window on that thread, the process handle count keeps increasing.
The handle type is File, and the FileName points to the WPF runtime DLLs, for example:
```
Type: File
FileName: C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App\8.0.22
```
Closing the Window does not release these handles. They are only released when the Dispatcher is shut down.
### Reproduction Steps
1. Create a .NET 8 WPF application.
2. Start a dedicated UI thread and run a Dispatcher as shown below:
```cs
private Dispatcher? _dispatcher;
private Thread? _thread;
private Dispatcher EnsureDispatcher()
{
if (_dispatcher == null)
{
using var evt = new AutoResetEvent(false);
_thread = new Thread(_ =>
{
_dispatcher = Dispatcher.CurrentDispatcher;
evt.Set();
Dispatcher.Run();
});
_thread.IsBackground = true;
_thread.SetApartmentState(ApartmentState.STA);
_thread.Start();
evt.WaitOne();
}
return _dispatcher!;
}
```
3. On this Dispatcher, repeatedly create a Window, call Show(), then Close().
4. Monitor the process using Task Manager or Process Explorer. The number of File handles increases continuously.
### Expected behavior
After calling Window.Close(), unnecessary handles should be released. Handle count should not grow indefinitely.
### Actual behavior
Handles are not released after closing the Window. They accumulate with each show/close cycle.
Calling Dispatcher.InvokeShutdown() releases them.
```cs
public void Dispose()
{
_dispatcher?.BeginInvokeShutdown(DispatcherPriority.Normal);
if (_thread != null && _thread.IsAlive)
{
_thread.Join();
}
_dispatcher = null;
_thread = null;
_runtime = null;
}
```
### Regression?
_No response_
### Known Workarounds
_No response_
### Impact
_No response_
### Configuration
- .NET: 8.0.22
- OS: Windows 11 22H2
- WPF: Microsoft.WindowsDesktop.App 8.0.22
### Other information
- The same behavior was observed on .NET 10 preview as well.
Contributor guide
Assessment
This issue has not been assessed yet.