DownloadFileCompleted / DownloadProgressChanged事件不起作用

时间:2018-04-09 16:58:13

标签: c# events webclient

我有一个后台工作者(如下所示)和DownloadFileCompleted / DownloadProgressChanged事件。经过几个小时的测试和大量的研究,我无法让它发挥作用。文件下载成功,但事件不会运行。我查看了很多文档页面并在这里搜索了这个问题,但它们似乎与我的情况不符......如果有人可以帮我解决这个问题,我将不胜感激!

    private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
            WebClient client = new WebClient();
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler (webClient_DownloadProgressChanged);
            client.DownloadFileCompleted += new AsyncCompletedEventHandler  (webClient_DownloadFileCompleted);

            client.DownloadFileAsync(new Uri(myUri), path);

        }
    }

    void webClient_DownloadFileCompleted(object s, AsyncCompletedEventArgs e)
    {
        Debug.WriteLine("Download completed!");
    }
    void webClient_DownloadProgressChanged(object s, DownloadProgressChangedEventArgs e)
    {
        Debug.WriteLine(e.BytesReceived);
    }

1 个答案:

答案 0 :(得分:0)

您的代码必须有其他错误,因为有效地运行相同的代码,它运行正常。

您是否确定您的程序在完成工作之前根本没有完成并关闭,因为BackgroundWorker不会使您的应用程序保持活动状态。

这是我的示例,前景线程使应用程序保持活动状态

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Net;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            new Thread(() =>
            {
                var client = new WebClient();
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
                client.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);

                client.DownloadFileAsync(new Uri("https://speed.hetzner.de/100MB.bin"), @"C:\Users\Luke\Desktop\100mb.bin");
            }).Start();
        }

        private static void webClient_DownloadFileCompleted(object s, AsyncCompletedEventArgs e)
        {
            Debug.WriteLine("Download completed!");
        }
        private static void webClient_DownloadProgressChanged(object s, DownloadProgressChangedEventArgs e)
        {
            Debug.WriteLine(e.BytesReceived);
        }
    }
}