Aman Sharma
Aman Sharma

Reputation: 698

How to make DownloadOperation to call ProgressChanged event more frequently?

I'm working on a UWP app to download some files over the internet. I use BackgroundDownloader class to download them in background. Here is piece of my code.

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);

All works fine but I notice a strange behavior. I update the data model in progressChanged method that notifies and updates the UI. But when downloading a file the progressChanged event is fired when about 1MB of file has downloaded on a slow internet connection, and when I pause the download and resume it, it fires that event let say every few KBs. I want to know that is there any way of configuring how frequently the ProgressChanged event is fired. I've searched the internet but found nothing. Please help.

Upvotes: 1

Views: 570

Answers (1)

Jay Zuo
Jay Zuo

Reputation: 15758

Thanks for your feedback. I can see similar behavior in my side. After pause and resume the download operation, the progressChanged handler is invoked more frequently. However, there is no API can control the frequency the progress callback been called. The handler set in Progress<DownloadOperation> constructor will be invoked each time the Windows Runtime method reports a progress notification. But this implementation is underlying, we can not control it.

If you do want to increase the frequency, a ugly workaround may be pausing and resuming the download operation in code behind when download operation first started. For example, we can add a flag to identify download operation first started.

private bool firstStart = true;

And then in progressChanged handler, pause and resume the download operation.

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

This is not a good practice and I've report this issue internally. I'll update my answer once have any progress.

Upvotes: 1

Related Questions