【问题标题】:Download file async using WebClient doens't work使用 WebClient 异步下载文件不起作用
【发布时间】:2015-08-19 20:15:33
【问题描述】:

我正在使用 C# 在 VS15 中制作控制台应用程序。 这是我的下载类:

class DownloadGamefile
{
    public  void DownloadFile(string address, string location)
    {
        WebClient client = new WebClient();
        Uri Uri = new Uri(address);

        client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);

        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgress);
        client.DownloadFileAsync(Uri, location);

    }

    private void DownloadProgress(object sender, DownloadProgressChangedEventArgs e)
    {
        // Displays the operation identifier, and the transfer progress.
        Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...",
            (string)e.UserState,
            e.BytesReceived,
            e.TotalBytesToReceive,
            e.ProgressPercentage);
    }

    private void Completed(object sender, AsyncCompletedEventArgs e)
    {
        if (e.Cancelled == true)
        {
            Console.WriteLine("Download has been canceled.");
        }
        else
        {
            Console.WriteLine("Download completed!");
        }
    }
}

这是我的主要内容:

class Program
{
    static void Main(string[] args)
    {

        DownloadGamefile DGF = new DownloadGamefile();

        DGF.DownloadFile("URL", @"C:\Users\LocDaiLe\Desktop\file.file");

    }
}

文件出现在正确的文件夹中,但大小为 0 字节,我的控制台没有显示任何下载进度。

【问题讨论】:

  • 可能你的应用在下载完成之前就已经存在,调用DownloadFile后尝试Console.ReadLine()
  • 感谢您的回复@cDima,但我不明白为什么会这样?我只使用一个控制台应用来测试它。

标签: c# asynchronous download webclient


【解决方案1】:

由于异步调用不会阻塞当前线程,我的猜测是 DownloadFileAsync (https://msdn.microsoft.com/en-us/library/ms144196(v=vs.110).aspx) 立即返回,导致您的 DownloadFile 也立即返回。这将在文件完成下载之前结束程序执行。

您需要阻塞线程,直到文件完成下载。您是否考虑过使用 .NET 4.5 (https://msdn.microsoft.com/en-us/library/hh191443.aspx) 中的 async/await?您还可以使用 Progress/Completed 事件来同步您的线程,以便应用程序在文件完成之前不会退出。 Console.ReadLine() 也应该阻塞当前线程,直到按下 Enter。

我扩展了您的代码以支持线程阻塞。这将使主线程在检查之间休眠 1 秒,直到文件完成。我使用关键字“volatile”(https://msdn.microsoft.com/en-us/library/x13ttww7.aspx)来确保始终获取最新的值。这对于多线程很重要。 _completed = true 位于 if/else 之外,因为我们希望它即使被取消也能退出。如果需要,您可以扩展此解决方案以处理取消的下载。

class DownloadGamefile
{
    private volatile bool _completed;

    public void DownloadFile(string address, string location)
    {
        WebClient client = new WebClient();
        Uri Uri = new Uri(address);
        _completed = false;

        client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);

        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgress);
        client.DownloadFileAsync(Uri, location);

    }

    public bool DownloadCompleted { get { return _completed; } }

    private void DownloadProgress(object sender, DownloadProgressChangedEventArgs e)
    {
        // Displays the operation identifier, and the transfer progress.
        Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...",
            (string)e.UserState,
            e.BytesReceived,
            e.TotalBytesToReceive,
            e.ProgressPercentage);
    }

    private void Completed(object sender, AsyncCompletedEventArgs e)
    {
        if (e.Cancelled == true)
        {
            Console.WriteLine("Download has been canceled.");
        }
        else
        {
            Console.WriteLine("Download completed!");
        }

        _completed = true;
    }
}

class Program
{
    static void Main(string[] args)
    {

        DownloadGamefile DGF = new DownloadGamefile();

        DGF.DownloadFile("URL", @"C:\Users\LocDaiLe\Desktop\file.file");

        while (!DGF.DownloadCompleted)
            Thread.Sleep(1000);
    }
}

【讨论】:

  • 感谢您的回复@TomA。我是 C# 线程编程的新手。如何在下载完成之前阻止当前线程 - 不使用 Console.ReadLine()?
  • 非常感谢。现在我明白了它是如何工作的 - 竖起大拇指!
  • 最后一个问题@TomA。我想制作一个可以从服务器下载文件的 WPF 应用程序。这个下载代码不会冻结我的 GUI 线程吗?
  • 是的,这种线程阻塞方法永远不应该在主线程的 UI 应用程序中使用。它将使应用程序无用,直到它停止调用 Thread.Sleep。如果要在 WPF/WinForm 中实现此功能,则不需要执行任何线程阻塞,因为与控制台应用程序不同,UI 应用程序在用户关闭它之前不会尝试退出。当 main 方法返回时,控制台应用程序退出。
  • async/await 也值得研究,它是 .NET 4.5 中添加的一项很棒的新功能,有助于将异步操作与您的 UI 同步。它消除了对 Completed 事件的需要,因为它将从当前方法返回并在操作完成时从返回的位置返回。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多