使用同步下载跟踪DownloadProgress

时间:2014-06-26 08:18:18

标签: c# .net

基本上我想做这样的事情:

using (WebClient wc = new WebClient())
{
    wc.DownloadProgressChanged += (sender, args) =>
        {
            progress = (float) args.BytesReceived / (float) args.TotalBytesToReceive;
        };
    wc.DownloadFile(new Uri(noLastSegment + file), path);
}

这不起作用,因为仅针对DownloadFileAsync等异步下载启动了进度。

1 个答案:

答案 0 :(得分:2)

如果你可以显示进度,通常你有一些其他线程就像一个UI线程,但是你可能有一个控制台应用程序或其他东西。您可以轻松使用某种等待句柄并在下载完成后进行设置。

using (var completedEvent = new ManualResetEventSlim(false))
using (WebClient wc = new WebClient())
{
    wc.DownloadFileCompleted += (sender, args) => 
    {
        completedEvent.Set();
    };
    wc.DownloadProgressChanged += (sender, args) =>
    {
        progress = (float) args.BytesReceived / (float) args.TotalBytesToReceive;
    };
    wc.DownloadFileAsync(new Uri(noLastSegment + file), path);
    completedEvent.Wait();
}