计时器在Xamarin.Forms中的System.Threading命名空间中不存在。

3

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

我如何在Xamarin.Forms中使用相同的类? (我想将我的项目从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.Timers 吗? - Sinatr
不,我在Xamarin.Android上有这个项目。 这个项目使用System.Threading.Timer。我需要将这个项目从Xamarin.Android转移到Xamarin.Forms。 - Kirill
我理解你的意思是,你只需要延迟执行一个方法而不需要定期调用它,对吗? - Wosi
3个回答

8

我也使用 TimerCallback 和 Change 方法。 - Kirill
你需要传递一个计时器回调函数作为第二个参数。它是一个返回bool类型的方法。当你想再次执行该回调函数时,返回true;当你想停止它时,返回false - Wosi
实际上,您可以在此处找到文档:http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/platform-specifics/#Device.StartTimer - JamesMontemagno
现在,如果您的目标是netstandard2,那么System.Threading.Timer在Xamarin.Forms中可用。 - Leotsarev

5

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

我如何使用TimerCallback和Change方法? - Kirill
这是一个很好的解决方案。一个问题:当我不再需要计时器时,如何停止它? - tatmanblue
它继承自CancellationToken,因此您可以在计时器对象上执行.Cancel()方法。这个方法是有效的,因为内部它会检查IsCancellationRequested并将此Token传递给Task.Delay()调用。但是您自己的回调函数将不会接收到此token。您可以更改代码以添加此功能。 - dlxeon

0

嗨,我在Xamarin.forms中找到了计时器的解决方案

  1. Device.StartTimer(TimeSpan.FromMilliseconds(1000), OnTimerTick); // TimeSpan.FromMilliseconds(1000) 指定时间为毫秒 //OnTimerTick 是将要执行并返回布尔值的函数

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接