3 回答
TA贡献1830条经验 获得超3个赞
class SizeQueue<T>{ private readonly Queue<T> queue = new Queue<T>(); private readonly int maxSize; public SizeQueue(int maxSize) { this.maxSize = maxSize; } public void Enqueue(T item) { lock (queue) { while (queue.Count >= maxSize) { Monitor.Wait(queue); } queue.Enqueue(item); if (queue.Count == 1) { // wake up any blocked dequeue Monitor.PulseAll(queue); } } } public T Dequeue() { lock (queue) { while (queue.Count == 0) { Monitor.Wait(queue); } T item = queue.Dequeue(); if (queue.Count == maxSize - 1) { // wake up any blocked enqueue Monitor.PulseAll(queue); } return item; } }}
bool closing;public void Close(){ lock(queue) { closing = true; Monitor.PulseAll(queue); }}public bool TryDequeue(out T value){ lock (queue) { while (queue.Count == 0) { if (closing) { value = default(T); return false; } Monitor.Wait(queue); } value = queue.Dequeue(); if (queue.Count == maxSize - 1) { // wake up any blocked enqueue Monitor.PulseAll(queue); } return true; }}
TA贡献1995条经验 获得超2个赞
TA贡献1815条经验 获得超13个赞
- 3 回答
- 0 关注
- 614 浏览
添加回答
举报