我能够以几乎令人尴尬的简单方式解决问题。后台任务取消时,手机关机,所以我附加了事件处理程序taskInstane.Canceled
事件在我的后台任务,只是添加了两行吧:
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("TaskCancelling.txt" CreateCollisionOption.OpenIfExists);
deferral.Complete();
然后,在前台应用程序,下面的代码运行每当启动应用:
foreach(IBackgroundTaskRegistration task in BackgroundTaskRegistration.AllTasks.Values)
{
if ((task as BackgroundTaskRegistration).Name == myTaskName)
{
if (await IsFilePresentInLocalDirectory("TaskCancelling.txt"))
{
//Task registration is present, but task isn't actually running.
//Unregister the useless task
(task as BackgroundTaskRegistration).Unregister(true);
//Delete the file
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("TaskCancelling.txt");
await file.DeleteAsync();
//Relaunch the DeviceUseTrigger task
RelaunchBackgroundTask();
}
}
}
private async Task<bool> IsFilePresentInLocalDirectory(string fileName)
{
try
{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch (Exception exc)
{
return false;
}
}
不言自明,我只是创建一个空的文本文件来创建一种日志任务取消的和我的每一个应用程序启动我检查一次看到它的文件存在。如果是,则重新启动任务并删除文件。
当您在取消事件中创建文件时,可能应该“等待”。如果没有它,技术上的延期可能会比文件创建更加完善,可能它不会发生,但以防万一。 – Romasz
是的,你是对的。我从内存中输入代码,因为该项目不在我身边。无论如何,纠正。 – Ali250
另外我认为最好在* LocalSettings *中使用一个特殊的变量而不是创建一个文件。访问设置更快,同步操作。 – Romasz