Timer doesn't contain in System.Threading at X

2020-03-26 07:04发布

I used System.Threading.Timer in Xamarin.Android.

How I can use the same class in Xamarin.Forms? (I want to transfer my project from Xamarin.Android in 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);
}

3条回答
叛逆
2楼-- · 2020-03-26 07:41

System.Threading.Timer is not available in PCL code. You can use the Xamarin.Forms.Device.StartTimer method instead as explained here: http://developer.xamarin.com/api/member/Xamarin.Forms.Device.StartTimer/

查看更多
相关推荐>>
3楼-- · 2020-03-26 07:43

For PCL you can create your own using async/await features. Another advantage of this approach - your timer method implementation can await on async methods inside timer handler

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);
    }
}

Usage:

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

private async Task OnTimer()
{
   // Do something
   await MyMethodAsync();
}
查看更多
不美不萌又怎样
4楼-- · 2020-03-26 07:44

Hi I found solution for the timer in Xamarin.forms

  1. Device.StartTimer(TimeSpan.FromMilliseconds(1000), OnTimerTick); // TimeSpan.FromMilliseconds(1000) specify the time in milisecond //OnTimerTick it is function that will be executed return boolean

    1. private bool OnTimerTick() { // code to be executed lblTime.Text = newHighScore .ToString(); newHighScore++; return true; }

I hope you get my point easily thanks.

查看更多
登录 后发表回答