Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 882483
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T12:26:01+00:00 2026-05-15T12:26:01+00:00

I’ve just begun to explore the TPL and have a design question. My Scenario:

  • 0

I’ve just begun to explore the TPL and have a design question.

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 at least one 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.

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.

//From the Director class
Task<Image>[] downloadTasks = collector.RetrieveImages(listOfURLs);

for (int i = 0; i < listOfURLs.Count; i++)
{
    //Wait for any of the remaining downloads to complete
    int completedIndex = Task<Image>.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<Image>[] RetrieveImages(List<string> urls)
{
    Task<Image>[] tasks = new Task<Image>[urls.Count];

    int index = 0;
    foreach (string url in urls)
    {
        string lambdaVar = url;  //Required... Bleh
        tasks[index] = Task<Image>.Factory.StartNew(() =>
            {
                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;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T12:26:02+00:00Added an answer on May 15, 2026 at 12:26 pm

    Typically you use WaitAny to wait for one task when you don’t care about the results of any of the others. For example if you just cared about the first image that happened to get returned.

    How about this instead.

    This creates two tasks, one which loads images and adds them to a blocking collection. The second task waits on the collection and processes any images added to the queue. When all the images are loaded the first task closes the queue down so the second task can shut down.

    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Drawing;
    using System.IO;
    using System.Net;
    using System.Threading.Tasks;
    
    namespace ClassLibrary1
    {
        public class Class1
        {
            readonly string _path = Directory.GetCurrentDirectory();
    
            public void Demo()
            {
                IList<string> listOfUrls = new List<string>();
                listOfUrls.Add("http://i3.codeplex.com/Images/v16821/editicon.gif");
                listOfUrls.Add("http://i3.codeplex.com/Images/v16821/favorite-star-on.gif");
                listOfUrls.Add("http://i3.codeplex.com/Images/v16821/arrow_dsc_green.gif");
                listOfUrls.Add("http://i3.codeplex.com/Images/v16821/editicon.gif");
                listOfUrls.Add("http://i3.codeplex.com/Images/v16821/favorite-star-on.gif");
                listOfUrls.Add("http://i3.codeplex.com/Images/v16821/arrow_dsc_green.gif");
                listOfUrls.Add("http://i3.codeplex.com/Images/v16821/editicon.gif");
                listOfUrls.Add("http://i3.codeplex.com/Images/v16821/favorite-star-on.gif");
                listOfUrls.Add("http://i3.codeplex.com/Images/v16821/arrow_dsc_green.gif");
    
                BlockingCollection<Image> images = new BlockingCollection<Image>();
    
                Parallel.Invoke(
                    () =>                   // Task 1: load the images
                    {
                        Parallel.For(0, listOfUrls.Count, (i) =>
                            {
                                Image img = RetrieveImages(listOfUrls[i], i);
                                img.Tag = i;
                                images.Add(img);    // Add each image to the queue
                            });
                        images.CompleteAdding();    // Done with images.
                    },
                    () =>                   // Task 2: Process images serially
                    {
                        foreach (var img in images.GetConsumingEnumerable())
                        {
                            string newPath = Path.Combine(_path, String.Format("{0}_rot.png", img.Tag));
                            Console.WriteLine("Rotating image {0}", img.Tag);
                            img.RotateFlip(RotateFlipType.RotateNoneFlipXY);
    
                            img.Save(newPath);
                        }
                    });
            }
    
            public Image RetrieveImages(string url, int i)
            {
                using (WebClient client = new WebClient())
                {
                    string fileName = Path.Combine(_path, String.Format("{0}.png", i));
                    Console.WriteLine("Downloading {0}...", url);
                    client.DownloadFile(url, Path.Combine(_path, fileName));
                    Console.WriteLine("Saving {0} as {1}.", url, fileName);
                    return Image.FromFile(Path.Combine(_path, fileName));
                }
            } 
        }
    }
    

    WARNING: The code doesn’t have any error checking or cancelation. It’s late and you need something to do right? 🙂

    This is an example of the pipeline pattern. It assumes that getting an image is pretty slow and that the cost of locking inside the blocking collection isn’t going to cause a problem because it happens relatively infrequently compared to the time spent downloading images.

    Our book… You can read more about this and other patterns for parallel programming at http://parallelpatterns.codeplex.com/
    Chapter 7 covers pipelines and the accompanying examples show pipelines with error handling and cancellation.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
I have a small JavaScript validation script that validates inputs based on Regex. I
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
This could be a duplicate question, but I have no idea what search terms
I don't have much knowledge about the IPv6 protocol, so sorry if the question
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.