DownloadFileAsync阻止我的应用程序

问题描述:

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

在下面的代码中,当用户在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; 
    } 
} 
+0

你怎么知道'DownloadFileAsync'导致你的用户界面冻结?你用什么'DownloadCompleted'?我敢打赌,这与此有关。 –

+0

截至目前我只是写了它,但没有使用它在任何地方。编辑代码。 – djkp

+0

“DownloadFileAsync”可能会阻塞UI线程的唯一方法是在文件完成下载之前它不会返回。那是怎么回事?如果您在该调用中放置了一个断点,然后执行,那么调试器会立即跳到下一行,还是直接进行方法调用直到文件已经下载? – jmcilhinney

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