在.net中从不同线程向阻塞集合队列添加数据是否是线程安全的。 [英] In .net Adding data to blocking collection queue from different threads is thread safe or not.

查看:81
本文介绍了在.net中从不同线程向阻塞集合队列添加数据是否是线程安全的。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hi
我想实现多线程Producer和单个Consumer,

我的目的是将来自不同线程的数据插入到我的队列中。队列中的数据由单个消费者处理。 br />
我怀疑是从不同线程向阻塞收集队列添加数据,以下实现是否是线程安全的。?

它是否在从不同线程添加到队列时插入任何重复记录?

请分享您的想法。



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.

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.
                }
            }
        }        
}

推荐答案

您可能需要阅读BlockCollection<t> [ ^ ],特别是备注部分。
You might want to read the documentation on BlockCollection<t>[^], specifically the Remarks section.


这篇关于在.net中从不同线程向阻塞集合队列添加数据是否是线程安全的。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆