Search code examples
winforms.net-5dispatcher.net-framework-version

How to access Dispatcher from a .Net 5 Winforms app


How can I use class System.Windows.Threading.Dispatcher from within a .Net 5.0 app?

According to the online documentation, it should be available.
https://learn.microsoft.com/en-us/dotnet/api/system.windows.threading.dispatcher?view=net-5.0.

Normally, in a .Net Framework app, I would just add a reference to assembly WindowsBase.dll. But since I'm using a .Net 5.0 project I can only reference Nuget Packages.
Cannot add assemblies to .Net Core application in Visual Studio 2019.

However, there does not seem to be a WindowsBase Nuget package.
https://www.nuget.org/packages?q=WindowsBase.

There is a package called Microsoft.Windows.Compatibility which according to its descriptions sounds like it should include the class; but it does not.
https://www.nuget.org/packages/Microsoft.Windows.Compatibility/6.0.0-preview.5.21301.5

Any suggestions?

Restrictions:

  • The project uses WinForms extensively. It's not viable to convert it to WPF.
  • The reason I use Dispatcher, it so that objects on different threads can call modifications to the UI. The UI does not exist when these objects are created, so passing controls to them is not an option (also, not very elegant IMO for business objects to know about buttons and stuff).

Solution

  • After looking carefully, I realized that as of today (17/Jun/2021) The Nuget Package Microsoft.Windows.Compatibility is still in pre-release. This means that by the time other people read this thread the class might be already included.

    If not, I found a workaround:

    1. Create a WPF class library
    2. Add a DispatcherWrapper class
    3. Add a private Dispatcher attribute.
    4. Add all the (needed) Dispatcher methods to the DispatcherWrapper class
    5. Add a project reference from the WinForms app to the WPF library.
    6. Use the DispatcherWrapper class instead of Dispatcher.

    However, after reading the comment from Jimi, I think that, when working on a Winforms application, it is more elegant to use SynchronizationContext instead of Dispatcher.