首页 > 解决方案 > System.Threading.Timer 未触发

问题描述

我正在编写一个应用程序,它将每 x 秒发送一次位置数据,并在后台运行。我正在调用以下方法。

    public void StartListening()
    {
        UpdateGpsService();
        if(CLLocationManager.LocationServicesEnabled)
        {
            locationManager.DesiredAccuracy = 10;

            nint taskId = UIApplication.SharedApplication.BeginBackgroundTask(() =>
           {
               timer = new Timer((o) =>
               {
                   CLLocation location = locationManager.Location;
                   Nmea nmea = new IOSNmea(location);
                   Gprmc gprmc = new Gprmc();
                   gprmc.url = this.Url;
                   gprmc.Id = this.DeviceId;
                   gprmc.GprmcString = nmea.ToString();

               }, null, 0, UpdateInterval * 1000);
           });

            App.Database.SaveItemAsync(new TodoItem() { key = LOCATOR_SERVICE_ID, value = taskId.ToString() });
        }
    }

但是,它似乎没有调用计时器回调中的代码。我尝试在其中放置一个断点,但它永远不会被调用。我的代码有明显问题吗?谢谢你的帮助。

标签: multithreadingxamarinxamarin.formsxamarin.iosbackground-process

解决方案


BeginBackgroundTask只告诉iOS您正在启动一个长时间运行的任务,并且处理程序不是用于执行该任务,但它是一个完成处理程序,当操作系统即将关闭它时调用......

Timer timer = null;
nint taskId = UIApplication.SharedApplication.BeginBackgroundTask(() =>
{
    // Clean up as the background task is begin shutdown by iOS
    timer?.Dispose();
});
timer = new Timer((o) =>
{
    Console.WriteLine("Timer Update");
}, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));

// Must call EndBackgroundTask when you are done with this...
// UIApplication.SharedApplication.EndBackgroundTask(taskId);

推荐阅读