using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace parkMonitor.tools { public class BlockingQueue { private BlockingCollection bQueue = new BlockingCollection(new ConcurrentQueue()); public void Enqueue(object message) { try { bQueue.Add(message); Console.WriteLine("入队后连接池个数:" + bQueue.Count); } catch (ObjectDisposedException ex) { Console.WriteLine(ex.Message + "对象已被释放"); } catch (InvalidOperationException ex) { Console.WriteLine(ex.Message + "已标记为已完成添加操作或队列未接收该项"); } } public object Dequeue() { object obj = null; try { obj = bQueue.Take(); Console.WriteLine("出队后连接池个数:" + bQueue.Count); } catch (ObjectDisposedException ex) { Console.WriteLine(ex.Message + "对象已被释放"); } catch (InvalidOperationException ex) { Console.WriteLine(ex.Message + "队列为空,无法获取"); } return obj; } public bool Dequeue(out object item, int millisecondsTimeout) { bool flag = false; try { flag = bQueue.TryTake(out item, millisecondsTimeout); Console.WriteLine("出队后连接池个数超时:" + bQueue.Count); } catch (ObjectDisposedException ex) { Console.WriteLine(ex.Message + "对象已被释放,连接池为空"); item = null; flag = false; } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(ex.Message + "millisecondsTimeout为-1表无期限超时,不能为非-1的负数"); item = null; flag = false; } return flag; } public int Count() { int counter = 0; try { counter = bQueue.Count(); Console.WriteLine("调用Count方法后" + counter); } catch (ObjectDisposedException ex) { Console.WriteLine(ex.Message + "对象已被释放"); } return counter; } } }