System.Threading.Timer无法启动

时间:2018-09-05 21:23:53

标签: multithreading xamarin xamarin.forms xamarin.ios background-process

我正在编写一个应用程序,该应用程序每隔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() });
        }
    }

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

1 个答案:

答案 0 :(得分:1)

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);