How do you use BindableObject.Dispatcher.DispatchAsync() in .NET MAUI?

dg2k 1,386 Reputation points
2022-07-16T09:58:02.663+00:00

While migrating a Xamarin-based app to .NET MAUI, I get a green squiggly line that advises me Device.InvokeOnMainThreadAsync(Func<task>) is obsolete, and instead to use BindableObject.Dispatcher.DispatchAsync().

The IntelliSense offers no hint as to what namespace BindableObject.Dispatcher.DispatchAsync() is under, nor binging or googling turns up any help.

Can you suggest how to use BindableObject.Dispatcher.DispatchAsync() as a replacement for Xamarin's Device.InvokeOnMainThreadAsync() ?

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,918 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rob Caplan - MSFT 5,422 Reputation points Microsoft Employee
    2022-07-17T21:31:03.753+00:00

    Microsoft.Maui.Controls.BindableObject is MAUI's root class for objects that can be bound - it is very high in the MAUI class hierarchy, and almost all MAUI objects inherit from it. See Data Binding Basic.

    Your app probably has a Shell or a ContentPage (or several) which can be a good source for the Dispatcher object

    An easy way to find info about it is to create a BindableObject variable (just type "BindableObject") in a class method, then right-click and select Go to Definition (F12 / ⌘D) to open it in the object browser and display documentation and where the class fits in the object hierarchy.

    BindableObject.Dispatcher will give you an IDispatcher , and you'll call its Dispatch(Action) (not DispatchAsync) with an Action similar to how you'd call InvokeOnMainThreadAsync(Action) in Xamarin.

    InvokeOnMainThread was an oversimplification - not all apps have a main thread or a singular UI thread. Associating the Dispatcher to a UI object (which will in turn be tied to a thread) is more general and better supports multi-window applications.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Murat Gungor 0 Reputation points
    2023-06-15T06:51:20.4566667+00:00

    This worked me well

     IDispatcherTimer timer4ImageShow;
     timer4ImageShow = Application.Current.Dispatcher.CreateTimer();
    
     timer4ImageShow.Interval = TimeSpan.FromSeconds(5);
                timer4ImageShow.Tick += (sender, e) => DisplayImage();
                timer4ImageShow.Start();
    
    0 comments No comments