Device.StartTimer和System.Threading.Timer两者使用后台线程,都能跨平台并与netstandard2兼容。 System.Threading.Timer的优点是非Xamarin特定。应该在何时选择哪种方法?使用Device.StartTimer可使用原生API。根据github.com/mono,System.Threading.Timer似乎使用专用线程来管理所有计时器。我是正确的吗,或者Xamarin使用另一种实现?
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出现之前实现的,在那个时候,计时器类对于PCL项目不可用。现在计时器类可用了,所以没有必要使用Device.StartTimer。但是那个API不会消失,因为仍有旧的项目依赖它。
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);
}
Device.StartTimer。 - Lucas Zhang
System.Threading.Timer和System.Timers.Timer之间进行选择。https://dev59.com/uXM_5IYBdhLWcg3wWRoF - Leotsarev