Device.StartTimer vs System.Threading.Timer in Xamarin.Forms

Viewed 4169

What's a benefits or drawbacks of using Device.StartTimer vs System.Threading.Timer?

Both are firing on background threads, both are cross-platform and netstandard2 compatible. System.Threading.Timer has a bonus points of being non-Xamarin specific.

What should I use and when?

  • Device.StartTimer use native APIs.
  • According to github.com/mono, System.Threading.Timer seems to use dedicated thread for all timers. Am I right, or do Xamarin use another implementation?
2 Answers

Official answer from Xamarin documentation team: https://github.com/MicrosoftDocs/xamarin-docs/issues/2243#issuecomment-543608668

Use either.

Device.StartTimer was implemented long before .NET Standard came along, and in those days the Timer class was unavailable to PCL projects. Now that the Timer class is available, there's no advantage/need to use Device.StartTimer. But that API won't vanish, because there will be older projects that still rely on it.

What's a benefits or drawbacks of using Device.StartTimer vs System.Threading.Timer?

Device.StartTimer use native apis. So you should invoke it prior because it starts a recurring timer on the UI thread using the device clock capabilities.

Device.StartTimer(TimeSpan.FromSeconds(30), () =>
{
    // Do something
   
    return true; // True = Repeat again, False = Stop the timer
});

And in specific platforms ,it will do the following .

iOS

public void StartTimer(TimeSpan interval, Func<bool> callback)
{
    NSTimer timer = NSTimer.CreateRepeatingTimer(interval, t =>
    {
        if (!callback())
            t.Invalidate();
    });
    NSRunLoop.Main.AddTimer(timer, NSRunLoopMode.Common);
}

Android

public void StartTimer(TimeSpan interval, Func<bool> callback)
{
    var handler = new Handler(Looper.MainLooper);
    handler.PostDelayed(() =>
    {
        if (callback())
            StartTimer(interval, callback);

        handler.Dispose();
        handler = null;
    }, (long)interval.TotalMilliseconds);
}
Related