System.Threading.Timer没有触发

问题描述 投票:0回答:1

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

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

multithreading xamarin xamarin.forms xamarin.ios background-process
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.