Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

EDIT

My implementation which expands on mm8's most appreciated answer.

Create a Property in my ViewModel

public Microsoft.UI.Dispatching.DispatcherQueue TheDispatcher { get; set; }

Then grab the dispatcher in my MainPage.xaml.cs codebehind Constructor must do in Main Window or Page code behind as this will return the UI thread

ViewModel.TheDispatcher = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread();

Now I have the dispatcher in my VM so its easy to use from the VM:

TheDispatcher.TryEnqueue(() =>
{
     // some ui thread work
});

Note: I didnt post this as an answer as there is one, this is my implementation to help anyone interested.

like image 249
tinmac Avatar asked Dec 06 '25 17:12

tinmac


2 Answers

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);
    ...
});
like image 127
mm8 Avatar answered Dec 08 '25 07:12

mm8


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.

like image 21
demonplus Avatar answered Dec 08 '25 07:12

demonplus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!