.NET C# 泛型队列

2021-05-18 17:28

阅读:625

标签: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 where T : class
    {
        private static ConcurrentQueue> _queue;

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

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

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

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

    }
}
2.使用方式:

//①.入队列

List ts = new List();

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

foreach(var t in ts){

QueueHelper.AddQueue(t);//入队列

}

//②.出队列

while(QueueHelper.Queue.Count>0){

T tempT = QueueHelper.DealQueue();

xxx //业务代码处理tempT

}

 

.NET C# 泛型队列

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

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


评论


亲,登录后才可以留言!