multithreading - 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() });
}
}
但是,它似乎没有调用计时器回调中的代码。我尝试在其中放置一个断点,但它永远不会被调用。我的代码有明显问题吗?谢谢你的帮助。
解决方案
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);
推荐阅读
- vaticle-typedb - 如何在 grakn 控制台中打破长线?
- php - if(is_uploaded_file($_FILES['file'][´tmp_name´]) 有问题,如果三个图像之一发生更改,则尝试更新信息
- sql - 滑动窗口上的不同计数
- mysql - SQL 查询查找只修了 4 学分课程的学生的姓名
- winforms - 在默认应用程序 WinForms (.NET Core) 中打开文件
- azure - 在 Azure Function 中执行 Import-Module 时已加载同名程序集错误
- php - 如何通过 SQL 选择要保存到的数据库
- node.js - 我正在使用 React 创建一个表单并收到此错误
- sql - 从字符串转换日期或时间时出错
- angular - 角度翻译不适用于角度 9