我认为,如果您正在进行新的开发并且可以使用 .NET 4 或更高版本,那么新的并发集合类(例如ConcurrentQueue )将为您提供更好的服务。
但是,如果您不能采取行动,并且严格回答您的问题,在 .NET 中,恕我直言,这有点简化,要实现 prod/cons 模式,您只需等待然后像下面那样脉冲(请注意,我在记事本)
// max is 1000 items in queue
private int _count = 1000;
private Queue<string> _myQueue = new Queue<string>();
private static object _door = new object();
public void AddItem(string someItem)
{
lock (_door)
{
while (_myQueue.Count == _count)
{
// reached max item, let's wait 'till there is room
Monitor.Wait(_door);
}
_myQueue.Enqueue(someItem);
// signal so if there are therads waiting for items to be inserted are waken up
// one at a time, so they don't try to dequeue items that are not there
Monitor.Pulse(_door);
}
}
public string RemoveItem()
{
string item = null;
lock (_door)
{
while (_myQueue.Count == 0)
{
// no items in queue, wait 'till there are items
Monitor.Wait(_door);
}
item = _myQueue.Dequeue();
// signal we've taken something out
// so if there are threads waiting, will be waken up one at a time so we don't overfill our queue
Monitor.Pulse(_door);
}
return item;
}
更新: 为了消除任何混乱,请注意Monitor.Wait释放锁,因此您不会遇到死锁