使用Device.StartTimer
与System.Threading.Timer
有什么好处或缺点?
两者都在后台线程上触发,都是跨平台和 netstandard2 兼容的。System.Threading.Timer
有一个额外的点,那就是非Xamarin特定的。
我应该使用什么以及何时使用?
- Device.StartTimer 使用本机 API。
- 根据 github.com/mono 的说法,
System.Threading.Timer
似乎对所有计时器使用专用线程。我是对的,还是 Xamarin 使用其他实现?
Xamarin文档团队的官方回答: https://github.com/MicrosoftDocs/xamarin-docs/issues/2243#issuecomment-543608668
使用其中之一。
Device.StartTimer 早在 .NET Standard 出现之前就已实现,在那些日子里,Timer 类对 PCL 项目不可用。现在 Timer 类可用,没有优势/需要使用 Device.StartTimer。但是这个API不会消失,因为会有更旧的项目仍然依赖它。
使用Device.StartTimer 与 Device.StartTimer的优缺点是什么System.Threading.Timer?
Device.StartTimer
使用本机 API。因此,应先调用它,因为它使用设备时钟功能在 UI 线程上启动定期计时器。
Device.StartTimer(TimeSpan.FromSeconds(30), () =>
{
// Do something
return true; // True = Repeat again, False = Stop the timer
});
并且在特定平台上,它将执行以下操作。
苹果
public void StartTimer(TimeSpan interval, Func<bool> callback)
{
NSTimer timer = NSTimer.CreateRepeatingTimer(interval, t =>
{
if (!callback())
t.Invalidate();
});
NSRunLoop.Main.AddTimer(timer, NSRunLoopMode.Common);
}
人造人
public void StartTimer(TimeSpan interval, Func<bool> callback)
{
var handler = new Handler(Looper.MainLooper);
handler.PostDelayed(() =>
{
if (callback())
StartTimer(interval, callback);
handler.Dispose();
handler = null;
}, (long)interval.TotalMilliseconds);
}