Ian*_*Ian 6 c# asp.net multithreading webclient download
我使用下面的代码从TFS服务器下载多个附件:
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);
}
Run Code Online (Sandbox Code Playgroud)
我想使用DownloadFileAsync下载多个文件,但我希望逐个下载它们.
有人可能会问"你为什么不使用同步的DownloadFile方法?" 这是因为:
这是我想到的解决方案:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这种方法存在一些问题:
有没有更好的方法使用WebClient.DownloadFileAsync一次下载一个文件?
谢谢!
要简化任务,您可以创建单独的附件列表:
list = new List<Attachment>(wi.Attachments);
Run Code Online (Sandbox Code Playgroud)
其中list是私有字段,类型为List <Attachment>.在此之后,您应该配置WebClient并开始下载第一个文件:
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);
}
Run Code Online (Sandbox Code Playgroud)
您的DownloadFileComplete处理程序应检查是否已下载所有文件并再次调用DownloadFileAsync:
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);
}
Run Code Online (Sandbox Code Playgroud)
此代码不是优化解决方案.这只是想法.
归档时间: |
|
查看次数: |
20818 次 |
最近记录: |