Click here to Skip to main content
15,895,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I want to implement multiple thread Producer and single Consumer,
My purpose is insert data from different threads into my Queue.The data from queue is processed by single consumer.
My doubt is adding data to blocking collection queue from different threads with below implementation is thread safe or not.?
Does it insert any duplicate records while adding to queue from different threads?
Kindly share your ideas.

C#
namespace SampleCollection
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void producer_Click(object sender, EventArgs e)
        {
            int i = 0;
            while (i <= 10)
            {
                i++;
                ProducerConsumer obj = new ProducerConsumer();
                ThreadPool.QueueUserWorkItem(obj.Producer, i);
            }
         
        }
    }
        public class ProducerConsumer
        {
            public static BlockingCollection<object> queue = new BlockingCollection<object>();
            public static Thread producerThread = null;
            static ProducerConsumer()
            {
                producerThread = new Thread(new ThreadStart(Consumer));
                producerThread.Start();
            }
            public void Producer(object item)
            {
               queue.Add(item);
            }
            public static void Consumer()
            {
                while (true)
                {
                    object item =queue.Take();                      
                    // Add my code to process the item here.
                }
            }
        }        
}
Posted
Updated 15-Apr-15 4:12am
v2

1 solution

You might want to read the documentation on BlockCollection<t>[^], specifically the Remarks section.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900