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

前端 未结 3 695
北海茫月
北海茫月 2021-01-14 11:29

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

How I can use the same class in Xamarin.Forms? (I want to transfer my projec

3条回答
  •  既然无缘
    2021-01-14 12:19

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

提交回复
热议问题