我是否需要在以下c#代码中使用锁定?

Emb*_*rja 4 c# multithreading thread-safety

在下面的代码中,我使用两个线程来共享这个示例中的sane资源,queue所以我需要使用lock,en-queueing or dequeuing如果是,那么为什么因为程序似乎工作正常.

class Program
{   
    static Queue<string> sQ = new Queue<string>();

    static void Main(string[] args)
    {
        Thread prodThread = new Thread(ProduceData);
        Thread consumeThread = new Thread(ConsumeData);
        prodThread.Start();
        consumeThread.Start();
        Console.ReadLine();
    }

    private static void ProduceData()
    {
        for (int i = 0; i < 100; i++)
        {
            sQ.Enqueue(i.ToString());               
        }
    }

    private static void ConsumeData()
    {
        while (true)
        {
            if (sQ.Count > 0)
            {
                string s = sQ.Dequeue();
                Console.WriteLine("DEQUEUE::::" + s);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Tre*_*ley 8

是的,System.Collections.Generic.Queue<T>不是同时写入和读取的线程安全.您需要在enquing或dequing之前锁定同一对象,或者如果您使用的是.NET 4/4.5,请使用System.Collections.Concurrent.ConcurrentQueue<T>该类并使用该TryDequeue方法.

你当前实现到目前为止没有引起问题的原因是由于Thread.Sleep(500)调用(不是你应该在生产代码中使用的东西),这意味着自从读取操作以来对它prodThreadconsumeThread读取没有写入队列需要不到500毫秒.如果删除Thread.Sleep赔率,它会在某个时刻抛出异常.