使用ApplicationTrigger的后台任务的多个实例

时间:2018-12-20 04:12:10

标签: c# .net uwp

我已经使用ApplicationTrigger触发器注册了后台任务,以在后台处理我的下载逻辑。从技术上讲,这是可行的,但一次只能下载一次。

注册正在进行的后台任务后,我将调用此方法:

public async void StartNew(DownloadTask task)
{
    DownloadTasks.Insert(0, task);
    await (App.DownloadBackgroundTask.Trigger as ApplicationTrigger).RequestAsync(new Windows.Foundation.Collections.ValueSet()
    {
        { "dl", 0 }
    });
}

此方法为第一个文件调用OnBackgroundActivated很好,但是此后的调用似乎被忽略了。

protected async override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
{
    base.OnBackgroundActivated(args);
    var d = args.TaskInstance.GetDeferral();
    if (args.TaskInstance == null)
        return;
    var name = args.TaskInstance.Task.Name;
    if(name == DownloadBackgroundTask.Name)
    {
        var id = (int)(args.TaskInstance.TriggerDetails as ApplicationTriggerDetails).Arguments["dl"];
        var dlTask = DownloadManager.DownloadTasks[id];
        await dlTask.Execute();
    }
    d.Complete();
}

这种类型的解决方案不是为多个实例设计的吗?处理这种情况的更好方法是什么?

这里我有什么想念的吗?或者这是一个错误的方法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

有名为BackgroundDownloader的系统默认类来处理后台下载。 BackgroundDownloader处理下载队列,因此可以一次下载多个文件。您可以使用GetCurrentDownloadsAsync()获取当前的下载队列。

Uri source = new Uri(serverAddressField.Text.Trim());
string destination = fileNameField.Text.Trim();
StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
                    destination, CreationCollisionOption.GenerateUniqueName);
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(source, destinationFile);
HandleDownloadAsync(download, true);

//下载进度

 private void DownloadProgress(DownloadOperation download)
        {
             double percent = 100;
            if (download.Progress.TotalBytesToReceive > 0)
            {
                percent = download.Progress.BytesReceived * 100 / download.Progress.TotalBytesToReceive;
            }           
        }