C#异步数据处理-WorkQueue

介绍

工作队列主要用于异步处理消息,详细介绍参考其他文章,这里主要提供使用方法

类似方法有List、HashMap、Dir,但是性能略逊一筹。

场景举例

硅晶片标刻:

通讯协议采用TCP协议

1、程序(Server)对接上游LAMA机器(Client),接受标刻条码信息。

2、程序(Client)控制激光打标机(Server),在硅晶片上标刻条码

3、程序(Client)读取扫码器(Server)读码信息,并于标刻条码信息对比

简单调用举例

struct recivecode
    {
        public string ID;
        public string STATION;
    }
WorkQueue<recivecode> l_queue = new WorkQueue<recivecode>();
WorkQueue<long> l_markcode = new WorkQueue<long>();
recivecode REC = new recivecode();
REC.ID = IDimforation;
REC.STATION = station;
l_queue.EnqueueBox(REC);
recivecode code = l_queue.TryDequeueBox();
Console.WriteLine(code.ID);

源代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Threading;

namespace laser_code
{
    /// <summary>
    /// 表示线程安全的队列
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class WorkQueue<T> : ConcurrentQueue<T>
    {
        private int _size = 100;
        private DateTime _time;
        public DateTime Time
        {
            get { return _time; }
            set { _time = value; }
        }
        public int Size
        {
            get { return _size; }
            set { _size = value; }
        }
        /// <summary>
        /// 移除并返回开始处的对象
        /// </summary>
        /// <returns></returns>
        public T TryDequeueBox()
        {
            T _obj = default(T);
            if (!this.IsEmpty)
            {
                this.TryDequeue(out _obj);
                this._time = DateTime.Now;
            }
            return _obj;
        }
        /// <summary>
        /// 将对象添加到队列末尾
        /// </summary>
        /// <param name="box"></param>
        public void EnqueueBox(T box)
        {
            if (this._size > this.Count)
            {
                this.Enqueue(box);
                _time = DateTime.Now;
            }
            else
            {
                this.Clear();
            }
        }
        /// <summary>
        /// 清空队列
        /// </summary>
        /// <returns></returns>
        public List<T> Clear()
        {
            T _obj = default(T);
            List<T> objectT = new List<T>();
            do
            {
                this.TryDequeue(out _obj);
                objectT.Add(_obj);
            } while (this.Count != 0);
            return objectT;
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/aqyl/p/12389318.html
今日推荐