Xamarin.Forms 处的 System.Threading 中不包含计时器

Timer doesn't contain in System.Threading at Xamarin.Forms

我在Xamarin.Android中使用了System.Threading.Timer

如何在 Xamarin.Forms 中使用相同的 class? (我想将我的项目从 Xamarin.Android 转移到 Xamarin.Forms)

public static System.Threading.Timer timer;
if (timer == null)
{
    System.Threading.TimerCallback tcb = MyMethod;
    timer = new System.Threading.Timer(tcb, null, 700, System.Threading.Timeout.Infinite);
}
else
{
    timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
    timer.Change(700, System.Threading.Timeout.Infinite);
}

System.Threading.Timer 在 PCL 代码中不可用。 您可以使用 Xamarin.Forms.Device.StartTimer 方法代替,如下所述: http://developer.xamarin.com/api/member/Xamarin.Forms.Device.StartTimer/

对于 PCL,您可以使用 async/await 功能创建自己的。这种方法的另一个优点 - 您的计时器方法实现可以等待计时器处理程序中的异步方法

public sealed class AsyncTimer : CancellationTokenSource
{
    public AsyncTimer (Func<Task> callback, int millisecondsDueTime, int millisecondsPeriod)
    {
        Task.Run(async () =>
        {
            await Task.Delay(millisecondsDueTime, Token);
            while (!IsCancellationRequested)
            {
                await callback();
                if (!IsCancellationRequested)
                    await Task.Delay(millisecondsPeriod, Token).ConfigureAwait(false);
            }
        });
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
            Cancel();

        base.Dispose(disposing);
    }
}

用法:

{
  ...
  var timer = new AsyncTimer(OnTimer, 0, 1000);
}

private async Task OnTimer()
{
   // Do something
   await MyMethodAsync();
}

您好,我在 Xamarin.forms

中找到了计时器的解决方案
  1. Device.StartTimer(TimeSpan.FromMilliseconds(1000), OnTimerTick); // TimeSpan.FromMilliseconds(1000) 以毫秒为单位指定时间 //OnTimerTick 是将要执行的函数 return boolean

    1. private bool OnTimerTick() { // 要执行的代码 lblTime.Text = newHighScore.ToString(); 新高分++; return 真; }

希望你能轻松理解我的意思 谢谢。