无法在BackgroundWorker中重用DownloadFile

我有一个简单的课:

public class DownloadFile { ... public string GetFile(string fileUrl, string pathOut) { using (WebClient wc = new WebClient()) { wc.DownloadFile(new Uri(fileUrl), pathOut); return pathOut; } } } 

我将其从BackgroundWorker调用2次,因为下载和安装2个文件(在此处执行自定义安装程序)。

问题是,第一个文件正常下载和安装,但第二个文件挂在wc2.DownloadFile(new Uri(fileUrl), pathOut); 线, 永远不会从那里出来

使用我每次使用时都处理WebClient ,所以我可以说:

 // Created BackgroundWorker so the UI doesn't get blocked and I can // can show the progress in a log... BackgroundWorker bkWrk = new BackgroundWorker(); bkWrk.WorkerReportsProgress = true; bkWrk.ProgressChanged += (s, e) => { ReportProgress(String.Format("Progress: {0}%", e.ProgressPercentage)); }; bkWrk.DoWork = delegate { DownloadFile fileManager = new DownloadFile(); fileManager.GetFile("http://domain.com/file_A.zip", "C:\\TEMP\\file_a.zip"); fileManager.GetFile("http://domain.com/file_B.zip", "C:\\TEMP\\file_b.zip"); }; bkWrk.RunWorkerAsync(); while(bkWrk.IsBusy) { // let's wait but fire all events Application.DoEvents(); } 

我没有看到任何问题…但事实是该文件挂起在DownloadFile方法,甚至尝试使用Microsoft符号在方法内导航没有运气。

甚至为请求添加了标题,但问题仍然存在

 wc.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0)" + " (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; 

我错过了一些明显的东西吗?

DownloadFile fileManager = new DownloadFile(); fileManager.GetFile(“http://domain.com/file_A.zip”,“C:\ TEMP \ file_a.zip”); fileManager.GetFile(“http://domain.com/file_B.zip”,“C:\ TEMP \ file_b.zip”);

你明白wc.DownloadFile不是Async方法吗? 这意味着您的后台工作人员必须在其工作完成之前下载第一个文件,然后下载第二个文件。

它确实…更大的问题,有时它下载两个文件没有问题: – / –

这只是意味着你等待足够长的时间才能完成两个动作。