简体   繁体   English

等待每个人-如何等待每个迭代完成?

[英]Await ForEach - How Do I Wait for Each Iteration To Complete?

I have a list of URL's List<string> . 我有一个URL List<string> I want to loop through each URL and download the content on the page. 我想遍历每个URL并下载页面上的内容。 The method that downloads the content from a URL is asynchronous. 从URL下载内容的方法是异步的。 I want to wait for each iteration to complete 我想等待每次迭代完成

foreach(string url in urlList)
{
    await DownloadPage(url);
}

Download Method: 下载方式:

private async Task DownloadPage(string url)
{
    // await Download content using HttpClient
    // Save file
}

What's happening at the moment is it's looping through each ForEach without waiting for it to complete. 目前正在发生的事情是,它循环遍历每个ForEach而无需等待其完成。

How can I achieve a solution so that it waits on each iteration for the page to download? 我如何实现一种解决方案,以使其在每次迭代时都等待页面下载?

instead of using the await keyword here, you could also call .Result on the method call and the task will be sure to be resolved and you will get the result from it right there on the spot. 除了await此处使用await关键字之外,您还可以在方法调用上调用.Result ,此任务一定可以解决,您可以从那里立即获得结果。 your code would look like so: 您的代码如下所示:

foreach(string url in urlList)
{
    DownloadPage(url).Result;
}

It sounds like you need the Task.WaitAll() method: 听起来您需要Task.WaitAll()方法:

// off the top of my head, syntax not guaranteed to be 100% correct :)
List<Task> tasks = new List<Task>();
foreach(string url in urlList) 
{
    tasks.Add(Task.Factory.StartNew(DownloadPage));
    Task.WaitAll(tasks.ToArray()); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM