如何使 DownloadOperation 更频繁地调用 ProgressChanged 事件?

How to make DownloadOperation to call ProgressChanged event more frequently?

我正在开发一个 UWP 应用程序以通过 Internet 下载一些文件。我使用 BackgroundDownloader class 在后台下载它们。这是我的一段代码。

public BackgroundDownloader backgroundDownloader = new BackgroundDownloader();
DownloadOperation downloadOperation = backgroundDownloader.CreateDownload(source, file);
Progress<DownloadOperation> progress = new Progress<DownloadOperation>(progressChanged);
CancellationTokenSource cancellationToken = new CancellationTokenSource();
await downloadOperation.StartAsync().AsTask(cancellationToken.Token, progress);

一切正常,但我注意到一个奇怪的行为。我在通知和更新 UI 的 progressChanged 方法中更新了数据模型。但是,当下载文件时,当在慢速互联网连接上下载了大约 1MB 的文件时,会触发 progressChanged 事件,当我暂停下载并恢复下载时,它会触发该事件,假设每隔几 KB。我想知道是否有任何方法可以配置触发 ProgressChanged 事件的频率。我在网上搜索过,但一无所获。请帮忙。

感谢您的反馈。我可以在我身边看到类似的行为。暂停并恢复下载操作后,progressChanged 处理程序被更频繁地调用。但是,没有 API 可以控制调用进度回调的频率。每次 Windows Runtime 方法报告进度通知时,都会调用 Progress<DownloadOperation> 构造函数中设置的处理程序。但是这个实现是底层的,我们无法控制。

如果您确实想增加频率,丑陋的 解决方法可能是在下载操作首次启动时在代码后面暂停和恢复下载操作。例如,我们可以添加一个标志来标识下载操作首先开始。

private bool firstStart = true;

然后在 progressChanged 处理程序中,暂停并恢复下载操作。

if (firstStart && currentProgress.Status == BackgroundTransferStatus.Running)
{
    download.Pause();
    await Task.Delay(100);
    download.Resume();
    firstStart = false;
}

这不是一个好的做法,我已经在内部报告了这个问题。一旦有任何进展,我会更新我的答案。