Xamarin Forms error using System.Timers and Sysem.Json

好久不见. 提交于 2019-12-02 03:52:44

PCL projects do not support System.Timer.

Xamarin Forms has a built in Timer to help workaround this limitation

Device.StartTimer (new TimeSpan (0, 0, 60), () => {
    // do something every 60 seconds
    return true; // runs again, or false to stop
});

If you want to start and stop the timer via buttons, you could do something like this:

bool timerStatus = false;

btnStart.Clicked += delegate {
  timerStatus = true;
  Device.StartTimer (new TimeSpan(h,m,x), () => {
     if (timerStatus) {
       // do work
     }
     return timerStatus;
  });
};

btnStop.Clicked += delegate {
  timerStatus = false;
};
Johannes Rudolph

Xamarin Forms libraries are Portable class libraries and as such, Timers are not part of the API for certain target platform combinations.

A good implementation replacement for a time would be an implementation using Task.Delay, marked as internal to avoid issues when using the PCL library on a platform that has timers available. You can use this code as a drop-in shim (source: link above):

internal delegate void TimerCallback(object state);

internal sealed class Timer : CancellationTokenSource, IDisposable
{
    internal Timer(TimerCallback callback, object state, int dueTime, int period)
    {
        Contract.Assert(period == -1, "This stub implementation only supports dueTime.");
        Task.Delay(dueTime, Token).ContinueWith((t, s) =>
        {
            var tuple = (Tuple<TimerCallback, object>)s;
            tuple.Item1(tuple.Item2);
        }, Tuple.Create(callback, state), CancellationToken.None,
            TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion,
            TaskScheduler.Default);
    }

    public new void Dispose() { base.Cancel(); }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!