Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Device.StartTimer is deprecated in MAUI what is the alternative?

Tags:

maui

I am trying to port an Xamarin.Forms app to .NET MAUI but have run into the deprecation of Device.StartTimer, whilst this obviously currently still works in MAUI, I am interested to find out what the alternative is?

Currently I have a wrapper class as follows:

public void Start()
{
   if (IsRunning)
   {
      return;
   }
   var wrapper = new TaskWrapper(Task, IsRecurring, true);
   Tasks.Add(wrapper);
   Device.StartTimer(Interval, wrapper.RunTask);
}

I tried replacing this with a System.Timers.Timer however this led to the issue of not being able to modify UI elements due to being on the wrong thread? The timer wrapper itself is used in multiple places so I can't use binding for example in this case either.

Is there actually a direct replacement for Device.StartTimer? Any assistance is greatly appreciated.

like image 742
Apqu Avatar asked Sep 12 '25 17:09

Apqu


1 Answers

Use Dispatcher

The Device timer is obsolete in MAUI.

You can create an IDispatcherTimer instance and subscribe to the Tick event like this:

var timer = Application.Current.Dispatcher.CreateTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += (s,e) => DoSomething();
timer.Start();

Update UI on MainThread

Depending on the context that you're using the timer in, you may need to use the MainThread.BeginInvokeOnMainThread() method to update UI elements, which is especially important on iOS:

void DoSomething()
{
    MainThread.BeginInvokeOnMainThread(() =>
    {
        //Update view here
    });
}

More info on UI main thread:

https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/appmodel/main-thread

like image 167
Julian Avatar answered Sep 14 '25 10:09

Julian



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!