首页 > 解决方案 > iOS Xamarin 计划计时器未触发

问题描述

我们在 Xamarin(不是Forms )项目中有一个调度程序逻辑,它存在了相当长的一段时间并且曾经工作过。随着 iOS 升级之一(可能是很久以前),调度程序停止触发事件。

为什么下面的计时器不是每 20 秒触发一次?该应用程序处于活动状态,屏幕已打开,并且我验证了初始化代码只运行了一次。

var interval = TimeSpan.FromSeconds(20);
Timer = NSTimer.CreateRepeatingScheduledTimer(interval, HandleScheduledEventMethod);

// ...

public void HandleScheduledEventMethod(NSTimer timer)
{
    // never executed, except for each call to Timer.Fire()
}

我按照 Apple文档中的建议将其添加到 NSRunLoop 中,但这也无济于事。

NSRunLoop.Main.AddTimer(Timer, NSRunLoopMode.Common);

标签: xamarinxamarin.ios

解决方案


AddTimer必须在主线程上调用,在后台线程上调用时不起作用。

DispatchQueue.MainQueue.DispatchQueue(() => {
  Timer = NSTimer.CreateRepeatingScheduledTimer(interval, HandleScheduledEventMethod);
  NSRunLoop.Main.AddTimer(Timer, NSRunLoopMode.Common);
})

推荐阅读