Note that there are some explanatory texts on larger screens.

plurals
  1. POParallel Task Library WaitAny Design
    text
    copied!<p>I've just begun to explore the PTL and have a design question.</p> <p>My Scenario: I have a list of URLs that each refer to an image. I want each image to be downloaded in parallel. As soon as <strong>at least one</strong> image is downloaded, I want to execute a method that does something with the downloaded image. That method should NOT be parallelized -- it should be serial.</p> <p>I think the following will work but I'm not sure if this is the right way to do it. Because I have separate classes for collecting the images and for doing "something" with the collected images, I end up passing around an array of Tasks which seems wrong since it exposes the inner workings of how images are retrieved. But I don't know a way around it. In reality there is more to both of these methods but that's not important for this. Just know that they really shouldn't be lumped into one large method that both retrieves and does something with the image.</p> <pre><code>//From the Director class Task&lt;Image&gt;[] downloadTasks = collector.RetrieveImages(listOfURLs); for (int i = 0; i &lt; listOfURLs.Count; i++) { //Wait for any of the remaining downloads to complete int completedIndex = Task&lt;Image&gt;.WaitAny(downloadTasks); Image completedImage = downloadTasks[completedIndex].Result; //Now do something with the image (this "something" must happen serially) //Uses the "Formatter" class to accomplish this let's say } /////////////////////////////////////////////////// //From the Collector class public Task&lt;Image&gt;[] RetrieveImages(List&lt;string&gt; urls) { Task&lt;Image&gt;[] tasks = new Task&lt;Image&gt;[urls.Count]; int index = 0; foreach (string url in urls) { string lambdaVar = url; //Required... Bleh tasks[index] = Task&lt;Image&gt;.Factory.StartNew(() =&gt; { using (WebClient client = new WebClient()) { //TODO: Replace with live image locations string fileName = String.Format("{0}.png", i); client.DownloadFile(lambdaVar, Path.Combine(Application.StartupPath, fileName)); } return Image.FromFile(Path.Combine(Application.StartupPath, fileName)); }, TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent); index++; } return tasks; } </code></pre>
 

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