我正在同步UWP APP
. 我正在使用后台任务和ApplicationTrigger
. 如果我调试我的代码(我的意思是如果附加了调试器)它可以工作,但是如果我运行已安装的应用程序,后台任务会在 10-20 分钟后终止。我必须同步很多文件,这需要 1-2 小时(我知道这很疯狂)。我在这里找到了信息:
https ://msdn.microsoft.com/en-us/windows/uwp/launch-resume/handle-a-cancelled-background-task ,但我不确定是否是这样,因为一切有内存就OK。
“注意对于除台式机以外的所有设备系列,如果设备内存不足,则可能会终止后台任务。如果没有出现内存不足异常,或者应用程序未处理该异常,则后台任务将在没有警告的情况下终止并且不引发 OnCanceled 事件。这有助于确保应用程序在前台的用户体验。您的后台任务应该设计为处理这种情况。
public async void Run(IBackgroundTaskInstance taskInstance)
{
deferral = taskInstance.GetDeferral();
_taskInstance = taskInstance;
var details = taskInstance.TriggerDetails as ApplicationTriggerDetails;
IEnumerable<string> filesUrls = details.Arguments.Select(x => x.Value as string).Distinct().ToList();
filesCount = filesUrls.Count();
downloader = CompletionGroupTask.CreateBackgroundDownloader();
var result = await Download(filesUrls, taskInstance, downloader);
if (result)
{
await Download(failedDownloads, taskInstance, downloader);
}
downloader.CompletionGroup.Enable();
deferral.Complete();
}
private async Task<bool> Download(IEnumerable<string> filesUrls, IBackgroundTaskInstance taskInstance, BackgroundDownloader downloader)
{
bool downloadFailed = false;
failedDownloads = new List<string>();
foreach (string url in filesUrls)
{
DownloadOperation download = null;
var uri = new Uri(url);
try
{
download = downloader.CreateDownload(uri, await CreateResultFileAsync(url.Split('/').Last()));
Task<DownloadOperation> startTask = download.StartAsync().AsTask();
await startTask.ContinueWith(task => OnDownloadCompleted(task, url));
}
catch
{
downloadFailed = true;
failedDownloads.Add(url);
}
}
return downloadFailed;
}
private void OnDownloadCompleted(Task<DownloadOperation> task, string url)
{
if (task.Status == TaskStatus.RanToCompletion)
{
completedDownloads++;
decimal progress = (completedDownloads / filesCount) * 100;
_taskInstance.Progress = Convert.ToUInt32(progress);
}
else if(task.Status == TaskStatus.Faulted)
{
failedDownloads.Add(url);
}
}
private async Task<IStorageFile> CreateResultFileAsync(string fileName)
{
var local = ApplicationData.Current.LocalFolder;
IStorageFile resultFile = await local.CreateFileAsync(fileName, CreationCollisionOption.FailIfExists);
return resultFile;
}
}
有谁知道为什么我的任务被杀死?