C#-等待多个文件下载完成

时间:2019-03-25 16:29:21

标签: c# async-await task

我有一个用C#编写的应用程序。在这个程序中,我需要下载多个文件。下载完所有文件后,我需要做其他事情。为了同时下载文件,我编写了以下内容:

private void DownloadFiles(string[] targets)
{
  var tasks = new List<Task>();
  foreach (var target in targets)
  {
    var task = DownloadFile(target);
    tasks.Add(task);
  }

  Task.WaitAll(tasks.ToArray());
}

private async Task DownloadFile(string target)
{
  using (var wc = new WebClient())
  {
    wc.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) => {
      Console.WriteLine(e.ProgressPercentage + "% downloaded.");
    }

    wc.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) => {
      Console.WriteLine(target + " was downloaded.");

      // TODO: Signal this "Task" is done
    }

    await wc.DownloadFileTaskAsync(target, localPath);
  }
}

也许我很困惑。我认为我需要在DownloadFileCompleted中做些事情。或者,也许await wc.DownloadFileTaskAsync行就足够了。

如何同时下载多个文件,但是要等到它们全部下载后才能继续?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

private void DownloadFiles(string[] targets)
{
    var tasks = new List<Task>();
    using (var wc = new WebClient())
    {
        foreach (var target in targets)
        {
            var task = DownloadFile(wc, target);
            tasks.Add(task);
        }
        Task.WaitAll(tasks.ToArray());
    }
}


private Task DownloadFile(WebClient wc, string target)
{            
    wc.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) =>
    {
         Console.WriteLine(e.ProgressPercentage + "% downloaded.");
    };

    wc.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) =>
    {
         Console.WriteLine(target + " was downloaded.");
         // TODO: Signal this "Task" is done
    };

    return wc.DownloadFileTaskAsync(target, localPath);
 }

我将WebClient移到了调用方法,因为您必须保持打开状态,直到所有下载完成为止(您不知道它们何时会进入DownloadFile方法中。)

另外,我从您的方法声明中删除了async,因为您不必等待方法中的某些内容。