C# Threading and Queues

后端 未结 5 1504
不知归路
不知归路 2021-02-02 01:13

This isn\'t about the different methods I could or should be using to utilize the queues in the best manner, rather something I have seen happening that makes no sense to me.

5条回答
  •  清酒与你
    2021-02-02 01:26

    Using Reflector, you can see that no, the count does not get increased until after the item is added.

    As Ben points out, it does seem as you do have multiple people calling dequeue.

    You say you are positive that nothing else is calling dequeue. Is that because you only have the one thread calling dequeue? Is dequeue called anywhere else at all?

    EDIT:

    I wrote a little sample code, but could not get the problem to reproduce. It just kept running and running without any exceptions.

    How long was it running before you got errors? Maybe you can share a bit more of the code.

    class Program
    {
        static Queue q = Queue.Synchronized(new Queue());
        static bool running = true;
    
        static void Main()
        {
            Thread producer1 = new Thread(() =>
                {
                    while (running)
                    {
                        q.Enqueue(Guid.NewGuid());
                        Thread.Sleep(100);
                    }
                });
    
            Thread producer2 = new Thread(() =>
            {
                while (running)
                {
                    q.Enqueue(Guid.NewGuid());
                    Thread.Sleep(25);
                }
            });
    
            Thread consumer = new Thread(() =>
                {
                    while (running)
                    {
                        if (q.Count > 0)
                        {
                            Guid g = (Guid)q.Dequeue();
                            Console.Write(g.ToString() + " ");
                        }
                        else
                        {
                            Console.Write(" . ");
                        }
                        Thread.Sleep(1);
                    }
                });
            consumer.IsBackground = true;
    
            consumer.Start();
            producer1.Start();
            producer2.Start();
    
            Console.ReadLine();
    
            running = false;
        }
    }
    

提交回复
热议问题