轻量级 Lock Free 线程安全的 Queue 的C#2.0实现

2.0里面又没有ConcurrentCollection的相关类

不得已,自己写了一个,

本来想用传统的lock实现的, 不过考虑到其中的操作非常轻量级...最终还是用了Lock Free

使用原子操作 InterLocked 替换掉常用的lock关键字

Try起头的方法都有尝试次数限制,超过限制以后就退出并返回false

public sealed class SafedQueue<T>
    {
        #region private Fields
        private int isTaked = 0;
        private Queue<T> queue = new Queue<T>();
        private int MaxCount = 1000 * 1000;
        #endregion

        public void Enqueue(T t)
        {
            try
            {
                while (Interlocked.Exchange(ref isTaked, 1) != 0)
                {
                }
                this.queue.Enqueue(t);
            }
            finally
            {
                Thread.VolatileWrite(ref isTaked, 0);
            }
        }

        public T Dequeue()
        {
            try
            {
                while (Interlocked.Exchange(ref isTaked, 1) != 0)
                {
                }
                T t = this.queue.Dequeue();
                return t;
            }
            finally
            {
                Thread.VolatileWrite(ref isTaked, 0);
            }
        }

        public bool TryEnqueue(T t)
        {
            try
            {
                for (int i = 0; i < MaxCount; i++)
                {
                    if (Interlocked.Exchange(ref isTaked, 1) == 0)
                    {
                        this.queue.Enqueue(t);
                        return true;
                    }
                }
                return false;
            }
            finally
            {
                Thread.VolatileWrite(ref isTaked, 0);
            }
        }

        public bool TryDequeue(out T t)
        {
            try
            {
                for (int i = 0; i < MaxCount; i++)
                {
                    if (Interlocked.Exchange(ref isTaked, 1) == 0)
                    {
                        t = this.queue.Dequeue();
                        return true;
                    }
                }
                t = default(T);
                return false;
            }
            finally
            {
                Thread.VolatileWrite(ref isTaked, 0);
            }
        }
    }

 

此条目发表在article分类目录,贴了标签。将固定链接加入收藏夹。