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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T00:42:15+00:00 2026-06-18T00:42:15+00:00

I have a situation where I have multiple producers and multiple consumers. The producers

  • 0

I have a situation where I have multiple producers and multiple consumers. The producers enters a job into a queue. I chose the BlockingCollection and it works great since I need the consumers to wait for a job to be found. However, if I use the GetConsumingEnumerable() feature the order of the items in the collection change… this is not what I need.

It even says in MSDN http://msdn.microsoft.com/en-us/library/dd287186.aspx
that it does not preserve the order of the items.

Does anyone know an alternative for this situation?

I see that the Take method is available but does it also provide a ‘wait’ condition for the consumer threads?

It says http://msdn.microsoft.com/en-us/library/dd287085.aspx

‘A call to Take may block until an item is available to be removed.’ Is it better to use TryTake? I really need the thread to wait and keep checking for a job.

  • 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-18T00:42:17+00:00Added an answer on June 18, 2026 at 12:42 am

    Take blocks the thread till something comes available.

    TryTake as the name implies tries to do so but returns a bool if it fails or succeeds.
    Allowing for more flex using it:

    while(goingOn){
       if( q.TryTake(out var){
          Process(var)
       }
       else{
          DoSomething_Usefull_OrNotUseFull_OrEvenSleep();
       }
    }
    

    instead of

    while(goingOn){
       if( var x = q.Take(){
          //w'll wait till this ever will happen and then we:
          Process(var)
       }
    }
    

    My votes are for TryTake 🙂

    EXAMPLE:

        public class ProducerConsumer<T> {
    
            public struct Message {
                public T Data;
            }
    
            private readonly ThreadRunner _producer;
            private readonly ThreadRunner _consumer;
    
            public ProducerConsumer(Func<T> produce, Action<T> consume) {
                var q = new BlockingCollection<Message>();
                _producer = new Producer(produce,q);
                _consumer = new Consumer(consume,q);
            }
    
            public void Start() {
                _producer.Run();
                _consumer.Run();
            }
    
            public void Stop() {
                _producer.Stop();
                _consumer.Stop();
            }
    
            private class Producer : ThreadRunner {
    
                public Producer(Func<T> produce, BlockingCollection<Message> q) : base(q) {
                    _produce = produce;
                }
    
                private readonly Func<T> _produce;
    
                public override void Worker() {
                    try {
                        while (KeepRunning) {
                            var item = _produce();
                            MessageQ.TryAdd(new Message{Data = item});
                        }
                    }
                    catch (ThreadInterruptedException) {
                        WasInterrupted = true;
                    }
                }
            }
    
            public abstract class ThreadRunner {
    
                protected readonly BlockingCollection<Message> MessageQ;
    
                protected ThreadRunner(BlockingCollection<Message> q) {
                    MessageQ = q;
                }
    
                protected Thread Runner;
                protected bool KeepRunning = true;
    
                public bool WasInterrupted;
    
                public abstract void Worker();
    
                public void Run() {
                    Runner = new Thread(Worker);
                    Runner.Start();
                }
    
                public void Stop() {
                    KeepRunning = false;
                    Runner.Interrupt();
                    Runner.Join();
                }
    
            }
    
            class Consumer : ThreadRunner {
    
                private readonly Action<T> _consume;
    
                public Consumer(Action<T> consume,BlockingCollection<Message> q) : base(q) {
                    _consume = consume;
                }
    
                public override void Worker() {
                    try {
                        while (KeepRunning) {
                            Message message;
                            if (MessageQ.TryTake(out message, TimeSpan.FromMilliseconds(100))) {
                                _consume(message.Data);
                            }
                            else {
                                //There's nothing in the Q so I have some spare time...
                                //Excellent moment to update my statisics or update some history to logfiles
                                //for now we sleep:
                                Thread.Sleep(TimeSpan.FromMilliseconds(100));
                            }
                        }
                    }
                    catch (ThreadInterruptedException) {
                        WasInterrupted = true;
                    }
                }
            }
        }
    
    }
    

    USAGE:

    [Fact]
    public void ConsumerShouldConsume() {
    
        var produced = 0;
        var consumed = 0;
    
        Func<int> produce = () => {
            Thread.Sleep(TimeSpan.FromMilliseconds(100));
            produced++;
            return new Random(2).Next(1000);
        };
    
        Action<int> consume = c => { consumed++; };
    
        var t = new ProducerConsumer<int>(produce, consume);
        t.Start();
        Thread.Sleep(TimeSpan.FromSeconds(5));
        t.Stop();
    
        Assert.InRange(produced,40,60);
        Assert.InRange(consumed, 40, 60);
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a situation where I need to insert multiple records/batch insert into a
I have a situation where I need the Checker enum below used in multiple
I have a situation here where I need to distribute work over to multiple
I have a situation where I need to match an objects to multiple tags
I have situation where I need to authenticate a client across multiple web services.
I have a situation where I need multiple renders to occur with the same
I have the following situation: multiple virtual directories under same application pool in IIS
The situation: I have multiple classes that should each hold a variable with a
I have a situation where I return results with multiple rows. I'm looking for
I have a situation where a Java Applet hangs after being opened multiple times.

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.