Skip to content

Handles keep increasing when repeatedly showing/closing a Window on a separate Dispatcher thread #11303

@YuuukiA

Description

@YuuukiA

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:
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!;
}
  1. On this Dispatcher, repeatedly create a Window, call Show(), then Close().
  2. 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.

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions