阻塞式队列应用介绍
阻塞式队列在多线程应用中比较常见,比如做为 生产者,消费者 共享队列。 常见流程如下:
c# 提供阻塞队列如: BlockingCollection ,了解原理后,自个写了一个队列:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Camera.COMMON { /// <summary> /// 阻塞消息队列 /// </summary> /// <typeparam name="T"></typeparam> public class BlockingList<T> { public object LockObj = new object(); public System.Threading.ManualResetEvent manu = new System.Threading.ManualResetEvent(true); Queue<T> queue = new Queue<T>(); /// <summary> /// 从队列批量取出数据 /// </summary> /// <returns></returns> public T[] Take() { T[] tArray = null; while (tArray == null || tArray.Length == 0) { if (queue.Count == 0) manu.WaitOne(); lock (LockObj) { tArray = queue.ToArray(); queue.Clear(); manu.Reset(); } } return tArray; } /// <summary> /// 从队列批量取出数据,逐一回调执行 /// </summary> /// <param name="CallBack"></param> public void Take(Action<T> CallBack) { if (CallBack == null) throw new Exception("CallBack fun is null!"); T[] result = Take(); foreach (T t1 in result) { CallBack(t1); } } /// <summary> /// 向队列添加一个元素 /// </summary> /// <param name="data"></param> public void Add(T data) { lock (LockObj) { queue.Enqueue(data); manu.Set(); } } } }