WebClient.DownloadFileAsync - 一次下载一个文件 [英] WebClient.DownloadFileAsync - Download files one at a time
问题描述
我正在使用以下代码从 TFS 服务器下载多个附件:
I am using the code below to download multiple attachments from a TFS server:
foreach (Attachment a in wi.Attachments)
{
WebClient wc = new WebClient();
wc.Credentials = (ICredentials)netCred;
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
wc.DownloadFileAsync(a.Uri, "C:\" + a.Name);
}
我想使用 DownloadFileAsync 下载多个文件,但我希望它们一个一个地下载.
I would like to download multiple files using DownloadFileAsync, but I want them to be downloaded one by one.
有人可能会问为什么不直接使用同步 DownloadFile 方法?"因为:
One may ask "Why don't you just use the synchronous DownloadFile method?" Its because:
- 我想利用 DownloadFileAsync 提供的事件.
- 我不想创建多个 Web 客户端实例以避免淹没服务器.
这是我想到的解决方案:
This is the solution that I thought of:
foreach (Attachment a in wi.Attachments)
{
WebClient wc = new WebClient();
wc.Credentials = (ICredentials)netCred;
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
wc.DownloadFileAsync(a.Uri, "C:\" + a.Name);
while (wc.IsBusy)
{
System.Threading.Thread.Sleep(1000);
}
}
但是,这种方法存在一些问题:
However, there are a couple of problems with this approach:
- Thread.Sleep() 正在锁定我的表单.我仍然需要创建自己的线程或使用BackgroundWorker.(我想尽可能避免这种情况)
- DownloadFileCompleted 事件在 ALL 文件下载后被触发.我不知道这是否是使用 System.Threading.Thread.Sleep(1000) 的副作用;
- The Thread.Sleep() is locking up my Form. I still need to make my own Thread or use BackgroundWorker. (I would like to avoid this as much as possible)
- The DownloadFileCompleted event is being triggered after ALL files has been downloaded. I don't know if this is a side-effect of using System.Threading.Thread.Sleep(1000);
是否有更好的方法使用 WebClient.DownloadFileAsync 一次下载一个文件?
Is there a better approach to download files one at a time using WebClient.DownloadFileAsync?
谢谢!
推荐答案
为了简化任务,您可以创建单独的附件列表:
To simplify the task you can create separated attachment list:
list = new List<Attachment>(wi.Attachments);
其中 list 是类型为 List
where list is private field with type List<Attachment>. After this you should configure WebClient and start downloading of first file:
if (list.Count > 0) {
WebClient wc = new WebClient();
wc.Credentials = (ICredentials)netCred;
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
wc.DownloadFileAsync(list[0].Uri, @"C:" + list[0].Name);
}
您的 DownloadFileComplete 处理程序应检查是否所有文件都已下载并再次调用 DownloadFileAsync:
Your DownloadFileComplete handler should check if not all files already downloaded and call DownloadFileAsync again:
void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) {
// ... do something useful
list.RemoveAt(0);
if (list.Count > 0)
wc.DownloadFileAsync(list[0].Uri, @"C:" + list[0].Name);
}
此代码不是优化的解决方案.这只是想法.
This code is not optimized solution. This is just idea.
这篇关于WebClient.DownloadFileAsync - 一次下载一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!