producerconsumerqueue.cs

来自「HeyCacher 高性能缓存方案(带源码) 1. 文件的所有权益归上传用户所有」· CS 代码 · 共 84 行

CS
84
字号
//===============================================================================
// CSDN HeyCache 
//===============================================================================
// 修改记录:[按最后修改时间倒排序]
// 2007.06.11 by tangwei
//
// 代码来源:参考于dotnet企业库3.0版
//===============================================================================
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;

namespace HeyCacher.Components.Scavenger
{
    /// <summary>
    /// 回收队列
    /// </summary>	
    public class ProducerConsumerQueue
    {
        private object lockObject = new Object();
        private Queue queue = new Queue();

        /// <summary>
        /// Gets the number of items in the queue.
        /// </summary>
        /// <value>
        /// The number of items in the queue.
        /// </value>
        public int Count
        {
            get { return queue.Count; }
        }

        /// <summary>
        /// Removes and returns the object at the beginning of the queue. 
        /// </summary>
        /// <returns>
        /// The object at the beginning of the queue.
        /// </returns>
        public object Dequeue()
        {
            lock (lockObject)
            {
                while (queue.Count == 0)
                {
                    if (WaitUntilInterrupted())
                    {
                        return null;
                    }
                }

                return queue.Dequeue();
            }
        }

        /// <summary>
        /// Adds the object at the end of the queue. 
        /// </summary>		
        public void Enqueue(object queueItem)
        {
            lock (lockObject)
            {
                queue.Enqueue(queueItem);
                Monitor.Pulse(lockObject);
            }
        }

        private bool WaitUntilInterrupted()
        {
            try
            {
                Monitor.Wait(lockObject);
            }
            catch (ThreadInterruptedException)
            {
                return true;
            }

            return false;
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?