加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – WebClient.DownloadFileAsync – 一次下载一个文件

发布时间:2020-12-15 04:31:17 所属栏目:百科 来源:网络整理
导读:我使用下面的代码从TFS服务器下载多个附件: foreach (Attachment a in wi.Attachments){ WebClient wc = new WebClient(); wc.Credentials = (ICredentials)netCred; wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted
我使用下面的代码从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);
}

我想使用DownloadFileAsync下载多个文件,但我希望逐个下载它们.

有人可能会问“你为什么不使用同步的DownloadFile方法?”这是因为:

>我想利用DownloadFileAsync提供的事件.
>我不想创建Webclient的多个实例以避免泛滥服务器.

这是我想到的解决方案:

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);
    }
}

但是,这种方法存在一些问题:

> Thread.Sleep()正在锁定我的表单.我仍然需要创建自己的Thread或使用BackgroundWorker. (我想尽可能避免这种情况)
>下载所有文件后,将触发DownloadFileCompleted事件.我不知道这是否是使用System.Threading.Thread.Sleep(1000)的副作用;

有没有更好的方法使用WebClient.DownloadFileAsync一次下载一个文件?

谢谢!

解决方法

要简化任务,您可以创建单独的附件列表:
list = new List<Attachment>(wi.Attachments);

其中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);
}

您的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);
}

此代码不是优化解决方案.这只是想法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读