Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First, I think you shouldn't base your logic on ids (unless you really have to). You should use references to the objects in the <code>SortedRecommendations</code> collection.</p> <p>Now, if you wanted to download only one file at a time, you could simply use <code>await</code>:</p> <pre><code>for (int i = 0; i &lt; SortedRecommendations.Count; i++) { string tempfilepath = filepath + SortedRecommendations[i].Aid + ".jpg"; if (File.Exists(tempfilepath)) continue; WebClient wc = new WebClient(); var recommendation = SortedRecommendations[i]; await wc.DownloadFileTaskAsync(new Uri(recommendation.Image.Replace("t.jpg", ".jpg")), tempfilepath); recommendation.Image = tempfilepath; } </code></pre> <p>But, if you wanted to start all of the downloads at the same time, like your <code>DownloadFileAsync()</code> code does, you could use <code>ContinueWith()</code> instead. And you don't need user state, that's what closures are for:</p> <pre><code>for (int i = 0; i &lt; SortedRecommendations.Count; i++) { string tempfilepath = filepath + SortedRecommendations[i].Aid + ".jpg"; if (File.Exists(tempfilepath)) continue; WebClient wc = new WebClient(); var recommendation = SortedRecommendations[i]; var downloadTask = wc.DownloadFileTaskAsync(new Uri(recommendation.Image.Replace("t.jpg", ".jpg")), tempfilepath); var continuation = downloadTask.ContinueWith(t =&gt; recommendation.Image = tempfilepath); tasks.Add(continuation); } await Task.WhenAll(tasks); </code></pre> <p>The best solution would probably be to download a limited number of files at once, not one or all of them. Doing that is more complicated and one solution would be to use <code>ActionBlock</code> from TPL Dataflow with <code>MaxDegreeOfParallelism</code> set.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload