如何在UWP BackgroundDownloader中计算下载速度?

时间:2018-10-26 03:31:57

标签: c# windows uwp

如何计算BackgroundDownload延迟/速度,例如367kb / s或5mb / s?

到目前为止,我知道BackgroundDownloadProgress类公开的唯一可能有用的字段是BytesReceivedTotalBytesToReceive。起初我以为我可以利用BytesReceived字段,但是后来我发现它是下载操作开始以来的累积字节,而不是新接收的块/字节。.

available fields in BackgroundDownloadProgress

我知道必须有一种方法来实现这一目标,因为我看到商店团队已在商店应用中实现了此目标:

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以使用一个以1秒为间隔计时的计时器,并计算两次计时之间下载的字节数。

以下代码未抛光,未将速度格式化为MB / s,下载完成后计时器不断计时,并且未处理取消/重新启动之类的异常情况,我只是向您提供了一个想法使用计时器和计数器进行计算。

DispatcherTimer timer;
ulong bytesReceivedAtLastTick;

private async void StartDownload()
{
    BackgroundDownloader downloader = new BackgroundDownloader();
    DownloadOperation download = downloader.CreateDownload(source, destinationFile);
    timer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1) };
    timer.Tick += (s, e) => {
        var bytesReceivedAtThisTick = download.Progress.BytesReceived;
        var bytesPerSecond = bytesReceivedAtThisTick - bytesReceivedAtLastTick;
        Log($"Download speed: {bytesPerSecond} B/s");
        bytesReceivedAtLastTick = bytesReceivedAtThisTick;
    };
    timer.Start();

    await download.StartAsync().AsTask(cts.Token, progressCallback);
}