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 4029702
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T11:22:44+00:00 2026-05-20T11:22:44+00:00

I’m trying to wrap my head around the whole Parallel Programming concept, mostly focusing

  • 0

I’m trying to wrap my head around the whole Parallel Programming concept, mostly focusing on Tasks, so I’ve been trying this scenario where, say, up to 9 Parallel Tasks would perform their work for a random period of time:

/// <remarks>
/// A big thank you to the awesome community of StackOverflow for 
/// their advice and guidance with this sample project
/// http://stackoverflow.com/questions/5195486/
/// </remarks>

RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();
byte[] buffer = new byte[4];
random.GetBytes(buffer);

// Creates a random number of tasks (not less than 2 -- up to 9)
int iteration = new Random(BitConverter.ToInt32(buffer, 0)).Next(2,9);
Console.WriteLine("Creating " + iteration + " Parallel Tasks . . .");
Console.Write(Environment.NewLine);

Dictionary<int, string> items = new Dictionary<int, string>();

for (int i = 1; i < iteration + 1; i++) // cosmetic +1 to avoid "Task N° 0"
{
    items.Add(i, "Task # " + i);
}

List<Task> tasks = new List<Task>();

// I guess we should use a Parallel.Foreach() here
foreach (var item in items)
{
    // Creates a random interval to pause the thread at (up to 9 secs)
    random.GetBytes(buffer);
    int interval = new Random(BitConverter.ToInt32(buffer, 0)).Next(1000, 9000);

    var temp = item;
    var task = Task.Factory.StartNew(state =>
    {
        Console.WriteLine(String.Format(temp.Value + " will be completed in {0} miliseconds . . .", interval));
        Thread.Sleep(interval);

        return "The quick brown fox jumps over the lazy dog.";

    }, temp.Value).ContinueWith(t => Console.WriteLine(String.Format("{0} returned: {1}", t.AsyncState, t.Result)));

    tasks.Add(task);
}

Task.WaitAll(tasks.ToArray());

But unfortunately they’re being handled sequentially instead of in parallel.

I’d be really glad if you guys could help me out here — maybe I should use a Parallel.ForEach instead of a regular one?

Again any advice would be really appreciated.

EDIT
Updated the code sample twice to reflect the contributions from the commenters.

  • 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-20T11:22:45+00:00Added an answer on May 20, 2026 at 11:22 am

    Calling Task.Result blocks. Since you’re doing that inside your foreach over items you end up creating one task and then waiting for it to finish before moving to the next item.

    try moving the call to Task.Result outside that foreach

    List<Task<string>> tasks = new List<Task<string>>();
    
    
    foreach (var item in items)
    {
        random.GetBytes(buffer);
        int interval = new Random(BitConverter.ToInt32(buffer, 0)).Next(1000, 9000);
    
        var task = Task.Factory.StartNew(state =>
        {
            Console.WriteLine(String.Format(item.Value + " will be completed in {0} miliseconds . . .", interval));
            Thread.Sleep(interval);
    
            return "The quick brown fox jumps over the lazy dog.";
    
        }, item.Value);
    
        tasks.Add(task);
    }
    
    foreach (var task in tasks)
    {
        Console.WriteLine(task.AsyncState + " returned: " + task.Result);
    } 
    

    EDIT

    As asked for in the comments. Here is a version that would print the result as each task finishes by using ConinueWith. The task list can now be a List<Task> again as well. The WaitAll call is still needed at the end to make sure the method doesn’t return until each task is done, but each task will print it’s result as it finishes.

    RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();
    byte[] buffer = new byte[4];
    random.GetBytes(buffer);
    
    // Creates a random number of tasks (not less than 2 -- up to 9)
    int iteration = new Random(BitConverter.ToInt32(buffer, 0)).Next(2, 9);
    Console.WriteLine("Creating " + iteration + " Parallel Tasks . . .");
    
    Dictionary<int, string> items = new Dictionary<int, string>();
    
    for (int i = 1; i < iteration + 1; i++) // cosmetic +1 to avoid "Task N° 0"
    {
        items.Add(i, "Parallel Task N° " + i);
    }
    
    List<Task> tasks = new List<Task>();
    
    // I guess we should use a Parallel.Foreach() here
    foreach (var item in items)
    {
        // Creates a random interval to pause the thread at (up to 9 secs)
        random.GetBytes(buffer);
        int interval = new Random(BitConverter.ToInt32(buffer, 0)).Next(1000, 9000);
    
        // http://stackoverflow.com/questions/5195486/
        var temp = item;
        var task = Task.Factory.StartNew(state =>
        {
            Console.WriteLine(String.Format(temp.Value + " will be completed in {0} miliseconds . . .", interval));
            Thread.Sleep(interval);
    
            return "The quick brown fox jumps over the lazy dog.";
    
        }, temp.Value).ContinueWith(t => Console.WriteLine(t.AsyncState + " returned: " + t.Result));
        tasks.Add(task);
    }
    
    Task.WaitAll(tasks.ToArray());
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
Does anyone know how can I replace this 2 symbol below from the string
this is what i have right now Drawing an RSS feed into the php,
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
Seemingly simple, but I cannot find anything relevant on the web. What is the
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and

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.