Search code examples
maui

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


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.


Solution

  • IDispatcherTimer timer;
    
    timer = Dispatcher.CreateTimer();
    timer.Interval = TimeSpan.FromMilliseconds(1000);
    timer.Tick += (s, e) =>
    {
        label.Text = DateTime.Now.ToString();
    };
    timer.Start();
    

    https://learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/button#press-and-release-the-button