For many Maui apps, class Mainthread
has convenient methods to run code on the main UI thread, from code that may be running in a background thread.
IMPORTANT: See caveats.
However, MainThread
lacks the equivalent of method IDispatch.DispatchDelayed
.
How do DispatchDelayed
in Maui (.Net 8 or above)?
- If this code is in code-behind of some UI object, instead of
MainThread
, use the UI object’sDispatcher
:
public partial class MainPage : ContentPage
{
...
public void SomeMethod()
{
// "this." added for clarity. Can be omitted.
this.Dispatcher.DispatchDelayed(TimeSpan.FromMilliseconds(100), () =>
{
// Your code here.
});
}
}
- If this code is in a non-UI class, the equivalent of
MainThread
isApplication.Current.Dispatcher
:
Application.Current.Dispatcher.DispatchDelayed(TimeSpan.FromMilliseconds(100), () =>
{
// Your code here.
});
As noted in the “See caveats” link in question, if an app opens more than one window (on a desktop OS), both MainThread
and Application.Current.Dispatcher
refer to the UI thread of the first window opened by the app. To dispatch on a second window’s UI thread, from non-UI-code, it is necessary to pass the window’s Dispatcher
to that code, so that DispatchDelayed
can be called on it.