为什么我的制作人有时会永远封锁?

时间:2016-09-22 08:57:43

标签: c# multithreading

我正在尝试使用C#Monitor中实现生产者/消费者类。 想法是消费者必须阻止,直到生产者有一些消费者的项目,但生产者应继续生产。 我的制作人制作了一些项目,然后等待/再睡一段时间再制作。

问题我看到制作人永远不会从Thread.Sleep(time)中醒来。 也许某处存在僵局。

请帮助我理解这一点。

就像说明一样,我不想使用BlockingCollection ... 这是我的代码......

public class ProducerConsumerEx
    {
        private object _objLocker = new object();
        private Thread _tProducer;
        private Queue<string> _producerQueue;
        private bool _keepProducing;
        public ProducerConsumerEx()
        {
            _keepProducing = false;
            _producerQueue = new Queue<string>();
            _tProducer = new Thread(Produce);
            _tProducer.IsBackground = true;
        }

        private void Produce()
        {
            while (_keepProducing)
            {
                Console.WriteLine($"PRODUCER {Thread.CurrentThread.ManagedThreadId} LOOP");
                lock (_objLocker)
                {
                    string item = DateTime.Now.ToString("HH:mm:ss");
                    _producerQueue.Enqueue(item);
                    Console.WriteLine($"PRODUCER {DateTime.Now.ToString("HH:mm:ss")} Thread {Thread.CurrentThread.ManagedThreadId} Inserted {item}");
                    Monitor.Pulse(_objLocker);
                    Console.WriteLine($"PRODUCER {DateTime.Now.ToString("HH:mm:ss")} Thread {Thread.CurrentThread.ManagedThreadId} AF Pulse {item}");
                }
                Console.WriteLine($"PRODUCER {DateTime.Now.ToString("HH:mm:ss")} Thread {Thread.CurrentThread.ManagedThreadId} BF Sleep");
                Thread.Sleep(10000);
                Console.WriteLine($"PRODUCER {DateTime.Now.ToString("HH:mm:ss")} Thread {Thread.CurrentThread.ManagedThreadId} AF Sleep");
            }
        }
        public void Start()
        {
            if (!_keepProducing)
            {
                _tProducer.Start();
                _keepProducing = true;
            }
        }
        public string Consume()
        {
            string val = default(string);
            Console.WriteLine($"CONSUMER {DateTime.Now.ToString("HH:mm:ss")} Thread {Thread.CurrentThread.ManagedThreadId} BF Consume");

            lock (_objLocker)
            {
                Console.WriteLine($"CONSUMER {DateTime.Now.ToString("HH:mm:ss")} Thread {Thread.CurrentThread.ManagedThreadId} BF Consume Inside");
                if (_producerQueue.Count > 0)
                {
                    val = _producerQueue.Dequeue();
                }
                else
                {
                    Console.WriteLine($"CONSUMER {DateTime.Now.ToString("HH:mm:ss")} Thread {Thread.CurrentThread.ManagedThreadId} WAITING");
                    Monitor.Wait(_objLocker);
                    //
                    if (_producerQueue.Count > 0)
                    {
                        val = _producerQueue.Dequeue();
                    }
                }
            }
            return val;
        }
    }

这个类的使用就像这样

static void Main(string[] args)
        {           
            ProducerConsumerEx pc = new ProducerConsumerEx();
            pc.Start();
            while (true)
            {
                string t = pc.Consume();
                Console.WriteLine($"Main {t}");
            }       
        }

2 个答案:

答案 0 :(得分:1)

为了实现消费者/生产者模式,我建议使用BlockingCollection

一个小例子:

    private BlockingCollection<string> _producerQueue;

    void Consume()
    {
        foreach (var item in _producerQueue.GetConsumingEnumerable())
        {
           //do some work there
        }
    }

    void Produce()
    {
       _producerQueue.Add("a string to consume");
    }

    public void Start()
    {
        Task.Factory.StartNew(Consume);
    }

来自MSDN:

https://msdn.microsoft.com/en-us/library/dd267312(v=vs.110).aspx

  

为线程安全提供阻止和绑定功能   实现IProducerConsumerCollection的集合。

你可以在那里找到一些例子:

http://dotnetpattern.com/csharp-blockingcollection

答案 1 :(得分:-1)

Monitor.Wait(_objLocker);lock (_objLocker)声明中。这样生产者永远不会添加和发信号通知消费者。您应该将Monitor.Wait(_objLocker);移到lock (_objLocker)

之外

类似于:(伪)

public string Consume()
{
    string val = default(string);
    Console.WriteLine($"CONSUMER {DateTime.Now.ToString("HH:mm:ss")} Thread {Thread.CurrentThread.ManagedThreadId} BF Consume");

    int count = 0;

    lock (_objLocker)
        count = _producerQueue.Count;

    if (count == 0)
    {
        Console.WriteLine($"CONSUMER {DateTime.Now.ToString("HH:mm:ss")} Thread {Thread.CurrentThread.ManagedThreadId} WAITING");
        Monitor.Wait(_objLocker);
    }

    lock (_objLocker)
        val = _producerQueue.Dequeue();

    return val;
}