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

  • Home
  • SEARCH
  • 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 9233147
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T06:28:57+00:00 2026-06-18T06:28:57+00:00

I am just now getting started with the task parallel library. The task in

  • 0

I am just now getting started with the task parallel library. The task in question is to process results in as parallel a manner as possible, but maintain the ordering of the results.

Also, an item can be added at any time until the flag is set indicating that no more items will be accepted.

Also, some clients will need to be notified once all results are completed (which will only occur once no more items are being accepted).

I have come up with the below simplified sample, which seems to work well in all my testing.

class Program
{
    static void Main(string[] args)
    {
        for (int i = 1; i < random.Next(5, 21); ++i)
        {
            AddItem(i);
        }

        finishedAddingItems = true;

        completion.Task.Wait();
        Console.WriteLine("Finished");
        Console.ReadKey();
    }

    static TaskCompletionSource<bool> completion = 
                            new TaskCompletionSource<bool>();

    static bool finishedAddingItems = false;

    static Random random = new Random();

    class QueueResult
    {
        public int data;
        public int IsFinished;
    }

    static ConcurrentQueue<QueueResult> queue = 
                           new ConcurrentQueue<QueueResult>();

    static object orderingLockObject = new object();

    static void AddItem(int i)
    {
        var queueItem = new QueueResult { data = i, IsFinished = 0 };

        queue.Enqueue(queueItem);

        Task.Factory
            .StartNew(() => 
            { 
                for (int busy = 0; 
                     busy <= random.Next(9000000, 90000000); 
                     ++busy) 
                { }; 
                Interlocked.Increment(ref queueItem.IsFinished); 
            })
            .ContinueWith(t =>
            {
                QueueResult result;

                //the if check outside the lock is to avoid tying up resources
                //needlessly, since only one continuation can actually process
                //the queue at a time.
                if (queue.TryPeek(out result) 
                    && result.IsFinished == 1)
                {
                    lock (orderingLockObject)
                    {
                        while (queue.TryPeek(out result) 
                               && result.IsFinished == 1)
                        {
                            Console.WriteLine(result.data);
                            queue.TryDequeue(out result);
                        }

                        if (finishedAddingItems && queue.Count == 0)
                        {
                            completion.SetResult(true);
                        }
                    }
                }
            });
    }
}

However, I am having trouble convincing myself whether or not there is a potential race condition where it is possible that an item would fail to get processed?

  • 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-06-18T06:28:58+00:00Added an answer on June 18, 2026 at 6:28 am

    I think that your code may not work correctly, because you didn’t declare IsFinished as volatile and you’re accessing it directly outside of a lock. In any case, using double-checked locking correctly is hard, so you shouldn’t do it unless you really have to.

    Also, your code is also quite a mess (having everything in one class, using int instead of bool, unnecessary ContinueWith(), …) and contains at least one more thread-safety issue (Random is not thread-safe).

    Because of all that, I suggest you learn about the more advanced parts of TPL. In your case, PLINQ sounds like the right solution:

    var source = Enumerable.Range(1, random.Next(5, 21)); // or some other collection
    
    var results = source.AsParallel()
                        .AsOrdered()
                        .WithMergeOptions(ParallelMergeOptions.NotBuffered)
                        .Select(i => /* perform your work here */);
    
    foreach (int i in results)
        Console.WriteLine(i);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am just getting started with Backbone.js , but it looks really interesting... Right
I am just getting started with SVG and am now trying out rotating objects.
I've been stuck on this for a day now! I'm just getting started with
Now i JUST started getting into joins, so I'm probably missing some core understanding
I am just getting started with celery,trying to run a periodic task. Configured *rabbitmq**
I have just finished https://github.com/overtone/overtone/wiki/Getting-Started which is fantastic. Now, I would like to do
I hope I'm asking this the right way but I am just getting started
I just upgraded jQuery to version 1.4.2 and I am now getting an error
We just switched to Glassfish V2. We are now getting errors when setting a
I just updated PHP 5.2.0 to 5.2.11 and now I am getting loads of

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.