如何实现进度便携式HttpClient的报告 [英] How to implement progress reporting for Portable HttpClient

查看:270
本文介绍了如何实现进度便携式HttpClient的报告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个库,意图在桌面上使用它(.NET 4.0及以上),电话(WP 7.5及以上)和Windows应用商店(Windows 8和以上)应用程序。

I'm writing a library with intentions to use it in desktop (.Net 4.0 and up), phone (WP 7.5 and up) and Windows Store (Windows 8 and up) apps.

图书馆有使用便携式HttpClient库从互联网上下载文件,并报告下载的进度的能力。

The library has the capability to download files from the Internet using Portable HttpClient library, and report the progress of the download.

我在这里搜索与互联网有关如何实施进度报告文档和代码示例/指南的休息,这个搜索导致我一事无成。

I search around here and the rest of the internet for documentations and code sample/guidelines on how to implement the progress reporting, and this search led me to nowhere.

有没有人有一篇文章,文档,指导原则,代码示例或任何帮助我实现这一目标?

Does anyone has an article, documentation, guideline, code sample or whatever to help me achieve this?

推荐答案

我写了下面的代码来实现的进展情况。该代码支持所有我想要的平台;但是,您需要参考以下的NuGet包:

I wrote the following code to implement progress reporting. The code supports all the platforms I wanted; however, you need to reference the following NuGet packages:


  • Microsoft.Net.Http

  • 微软.Bcl.Async

下面是代码:

public async Task DownloadFileAsync(string url, IProgress<double> progress, CancellationToken token)
{
    var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token);

    if (!response.IsSuccessStatusCode)
    {
        throw new Exception(string.Format("The request returned with HTTP status code {0}", response.StatusCode));
    }

    var total = response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L;
    var canReportProgress = total != -1 && progress != null;

    using (var stream = await response.Content.ReadAsStreamAsync())
    {
        var totalRead = 0L;
        var buffer = new byte[4096];
        var isMoreToRead = true;

        do
        {
            token.ThrowIfCancellationRequested();

            var read = await stream.ReadAsync(buffer, 0, buffer.Length, token);

            if (read == 0)
            {
                isMoreToRead = false;
            }
            else
            {
                var data = new byte[read];
                buffer.ToList().CopyTo(0, data, 0, read);

                // TODO: put here the code to write the file to disk

                totalRead += read;

                if (canReportProgress)
                {
                    progress.Report((totalRead * 1d) / (total * 1d) * 100);
                }
            }
        } while (isMoreToRead);
    }
}



在使用它很简单,只要:

The using it is as simple as:

var progress = new Microsoft.Progress<double>();
progress.ProgressChanged += (sender, value) => System.Console.Write("\r%{0:N0}", value);

var cancellationToken = new CancellationTokenSource();

await DownloadFileAsync("http://www.dotpdn.com/files/Paint.NET.3.5.11.Install.zip", progress, cancellationToken.Token);

这篇关于如何实现进度便携式HttpClient的报告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆