I am using the background task. The task working fine but will force close at some point. I have test application and keep it open for whole afternoon, if I remove the background task I have in the code, the crash didn't happen.
After I looked closely, probably missing a line of code to assign the task object invalid.
var siteId = Settings.CurrentSiteId;
if (siteId > 0 && !(new EntityBLL().IsInitial(siteId)))
{
var task = nint.MinValue;
task = UIApplication.SharedApplication.BeginBackgroundTask("bgEntityDownload", () =>
{
ServerEntity.TerminateAutoDownload(true);
UIApplication.SharedApplication.EndBackgroundTask(task);
task = UIApplication.BackgroundTaskInvalid;
completionHandler?.Invoke(UIBackgroundFetchResult.NewData);
});
AppLogger.Instance.AddLog(AppLogLevel.Information,
nameof(TimerDownload),
nameof(DownloadEntityFromServer),
"Background download starts", "");
var result = await ServerEntity.AutoDownload(siteId);
UIApplication.SharedApplication.EndBackgroundTask(task);
task = UIApplication.BackgroundTaskInvalid;
completionHandler?.Invoke(UIBackgroundFetchResult.NewData);
}
The line here :
var result = await ServerEntity.AutoDownload(siteId);
UIApplication.SharedApplication.EndBackgroundTask(task);
task = UIApplication.BackgroundTaskInvalid;
Is the line with task = UIApplicaition.BackgroundTaskInvalid is required after the work done.
It's not required, but a good practice that allows a system to spend its resources on different processes. Your background task will be force terminated after 180 seconds.