Trouble reusing DownloadFile inside a BackgroundWorker
I have a simple class:
public class DownloadFile
{
...
public string GetFile(string fileUrl, string pathOut)
{
using (WebClient wc = new WebClient())
{
wc.DownloadFile(new Uri(fileUrl), pathOut);
return pathOut;
}
}
}
that I call it from a BackgroundWorker
2 times as the process is to download and install 2 files (Doing a custom Installer here).
Problem is that, the first file downloads and installs normally, but the开发者_开发知识库 2nd file hangs on the wc2.DownloadFile(new Uri(fileUrl), pathOut);
line and never get's out from there!
using using
I'm disposing the WebClient
every time I use, so I could say:
// 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();
}
I do not see any problem here ... but the truth is that the file hangs on the DownloadFile
method, even tried using the Microsoft Symbols to navigate inside the method with no luck.
Even added a header to the request, but still, the problem remains
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)";
Am I missing something obvious here?
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");
You do understand that wc.DownloadFile isn't an Async method right? This means your background worker must download the first file, then the second file, before its work has been completed.
it does ... bigger problem, is that sometimes it download both files without a problem :-/ –
This just means you waited long enough for both actions to be completed.
精彩评论