按照伟大article的指示,我遇到了需要解决的问题。如何实现线程安全类队列的push和pop方法?
答案 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.