如何使用c#实现线程安全类队列的push和pop方法

时间:2016-03-02 10:32:41

标签: c# multithreading

按照伟大article的指示,我遇到了需要解决的问题。如何实现线程安全类队列的push和pop方法?

1 个答案:

答案 0 :(得分:1)

A simple lock would do just fine.

var synchro = new object();
var queue = new Queue<int>();
lock(synchro)
{
    queue.Enqueue(123); // Add to queue
}
lock(synchro)
{
    var num = queue.Dequeue(); // Remove from queue
}

Alternatively, you can use a ConcurrentQueue in combination with a BlockingCollection, but it's less flexible. For example you can't safely add or remove multiple items at the same time.