DownloadFileAsync阻止我的应用程序

时间:2017-05-04 04:58:31

标签: c# .net wpf downloadfileasync

我正在尝试下载一个大文件(大约1GB)我的服务器。当我开始下载时,我无法使用该应用程序直到下载完成。它阻止了用户界面并且没有响应。

在下面的代码中,我在UI上的用户下载按钮时调用DownloadFile方法。然后下载开始,但UI被冻结。

我读到DownloadFileAsync不会阻止用户界面。但在这里阻止。如何以正确的方式使用它。有几个答案,但在我测试时没有一个工作。

代码:

按钮通话:

private void Button_Click(object sender, RoutedEventArgs e)
{
        Debug.WriteLine("1");           
        DownloadGamefile DGF = new DownloadGamefile();
        Debug.WriteLine("2" + Environment.CurrentDirectory);
        DGF.DownloadFile("URL(https link to zip file)", Environment.CurrentDirectory + @"\ABC.zip");
        Debug.WriteLine("3");
 }

下载代码:

 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);

    }

    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;
    }
}

1 个答案:

答案 0 :(得分:0)

请参阅此link。实际问题是获得大量关于下载字节数的反馈(关于下载过程的进度)。采取计时器每2秒或任何时间取得进展,这解决了问题。

相关问题