Home > database >  How to get DispatcherQueue in WinUI 3 Desktop using Windows App SDK
How to get DispatcherQueue in WinUI 3 Desktop using Windows App SDK

Time:11-11

In WPF all controls inherit DispatcherObject & its easy to get to the Dispatcher.

How would I get the DispatcherQueue using WinUI 3 Windows App SDK and use it in a ViewModel?

CodePudding user response:

Yes, getting DispatcherQueue is different from WPF, it is something like that in WinUI3:

var dispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread();

After that you can use TryEnqueue method.

CodePudding user response:

Call the DispatcherQueue.GetForCurrentThread() API on the dispatcher thread.

If you create your view models on the dispatcher thread, you could call the method in the constructor or directly in the initializer as I demonstrated in your other question.

If you create your view models on a background thread, you will have to inject them with a DispatcherQueue that you create before on an actual dispatcher thread, e.g.:

DispatcherQueue dispatcherQueue = DispatcherQueue.GetForCurrentThread();

Task.Run(() => 
{
    ViewModel vm = new ViewModel(dispatcherQueue);
    ...
});
  • Related