使用DownloadDataAsync等待多个文件下载 [英] AWAIT multiple file downloads with DownloadDataAsync

查看:139
本文介绍了使用DownloadDataAsync等待多个文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个zip文件创建者,该创建者接受Urls的String[],并返回一个zip文件,其中包含String[]

I have a zip file creator that takes in a String[] of Urls, and returns a zip file with all of the files in the String[]

我认为会有很多这样的例子,但是我似乎找不到如何异步下载许多文件并在完成后返回"的答案.

I figured there would be a number of example of this, but I cannot seem to find an answer to "How to download many files asynchronously and return when done"

如何一次下载{n}个文件,并且仅在所有下载完成后才返回字典?

How do I download {n} files at once, and return the Dictionary only when all downloads are complete?

private static Dictionary<string, byte[]> ReturnedFileData(IEnumerable<string> urlList)
{
    var returnList = new Dictionary<string, byte[]>();
    using (var client = new WebClient())
    {
        foreach (var url in urlList)
        {
            client.DownloadDataCompleted += (sender1, e1) => returnList.Add(GetFileNameFromUrlString(url), e1.Result);
            client.DownloadDataAsync(new Uri(url));
        }
    }
    return returnList;
}

private static string GetFileNameFromUrlString(string url)
{
    var uri = new Uri(url);
    return System.IO.Path.GetFileName(uri.LocalPath);
}

推荐答案

  • 首先,您用async-await标记了您的问题,而没有实际使用它.确实没有理由再使用旧的异步范例了.
  • 异步等待所有并发的async操作完成,您应该使用Task.WhenAll,这意味着您需要在实际提取其结果之前将所有任务保留在某种构造(即字典)中
  • 最后,当您拥有所有结果时,只需将uri解析为文件名,然后从async任务中提取结果,即可创建新的结果字典.
    • First, you tagged your question with async-await without actually using it. There really is no reason anymore to use the old asynchronous paradigms.
    • To wait asynchronously for all concurrent async operation to complete you should use Task.WhenAll which means that you need to keep all the tasks in some construct (i.e. dictionary) before actually extracting their results.
    • At the end, when you have all the results in hand you just create the new result dictionary by parsing the uri into the file name, and extracting the result out of the async tasks.
    • async Task<Dictionary<string, byte[]>> ReturnFileData(IEnumerable<string> urls)
      {
          var dictionary = urls.ToDictionary(
              url => new Uri(url),
              url => new WebClient().DownloadDataTaskAsync(url));
      
          await Task.WhenAll(dictionary.Values);
      
          return dictionary.ToDictionary(
              pair => Path.GetFileName(pair.Key.LocalPath),
              pair => pair.Value.Result);
      }
      

      这篇关于使用DownloadDataAsync等待多个文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆