码迷,mamicode.com
首页 > Windows程序 > 详细

.NET C# 泛型队列

时间:2019-10-25 18:13:44      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:ace   services   empty   处理   list   name   xxx   eal   out   

1.QueueHelper

using System.Collections.Concurrent;
using System.Runtime.CompilerServices;

namespace WindowsFormsServer.Helper
{
    public static class QueueHelper<T> where T : class
    {
        private static ConcurrentQueue<StrongBox<T>> _queue;

        public static ConcurrentQueue<StrongBox<T>> Queue
        {
            get { return _queue ?? (_queue = new ConcurrentQueue<StrongBox<T>>()); }
        }

        public static void AddQueue(T t)
        {
            if (_queue == null)
                _queue = new ConcurrentQueue<StrongBox<T>>();
            _queue.Enqueue(new StrongBox<T>(t));
        }

        public static T DealQueue()
        {
            if (_queue == null)
                _queue = new ConcurrentQueue<StrongBox<T>>();
            if (_queue.Count > 0)
            {
                StrongBox<T> t;
                if (_queue.TryDequeue(out t)) return t.Value;   
            }
            return null;
        }

        public static void EmptyQueue()
        {
            if (_queue == null)
                _queue = new ConcurrentQueue<StrongBox<T>>();
            StrongBox<T> t;
            while(_queue.TryDequeue(out t))
                t.Value = default(T);
        }

    }
}
2.使用方式:

//①.入队列

List<T> ts = new List<T>();

xxx //此处批量为ts集合赋值

foreach(var t in ts){

QueueHelper<T>.AddQueue(t);//入队列

}

//②.出队列

while(QueueHelper<T>.Queue.Count>0){

T tempT = QueueHelper<T>.DealQueue();

xxx //业务代码处理tempT

}

 

.NET C# 泛型队列

标签:ace   services   empty   处理   list   name   xxx   eal   out   

原文地址:https://www.cnblogs.com/jeff151013/p/11739258.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!