Replies: 2 comments 2 replies
-
The recommended way is to use the public sealed partial class MainPage : Page
{
private DispatcherQueue _dispatcherQueue;
public MainPage()
{
this.InitializeComponent();
this.Loaded += MainPage_Loaded;
_dispatcherQueue = DispatcherQueue.GetForCurrentThread();
}
private async void MainPage_Loaded(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
{
// This works because this event handler is called on the UI thread.
Button button = new();
// This throws an exception because the button is not created on the UI thread.
await Task.Run(() =>
{
Button button = new();
});
// This works because the DispatcherQueue is used to create the button on the UI thread.
this.DispatcherQueue.TryEnqueue(() =>
{
Button button = new();
});
// This works because the DispatcherQueue is used to create the button on the UI thread.
_dispatcherQueue.TryEnqueue(() =>
{
Button button = new();
});
}
} |
Beta Was this translation helpful? Give feedback.
-
The big thing to remember is that the desktop windowing system means that you need a loop on UI threads to handle messages. Usually it is a loop along the lines of:
This means that there is one way to get back to the UI thread from any other thread if you have a window handle. There is also the concept of a message only window, which is a window that can never be made visible and only exists to receive messages. |
Beta Was this translation helpful? Give feedback.
-
How WinUI3 refreshes the UI thread in other threads
I've been stuck with this question for a long time, hope someone answers thank you
Beta Was this translation helpful? Give feedback.
All reactions