BlockingQueue.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace parkMonitor.tools
  8. {
  9. public class BlockingQueue
  10. {
  11. private BlockingCollection<object> bQueue = new BlockingCollection<object>(new ConcurrentQueue<object>());
  12. public void Enqueue(object message)
  13. {
  14. try
  15. {
  16. bQueue.Add(message);
  17. Console.WriteLine("入队后连接池个数:" + bQueue.Count);
  18. }
  19. catch (ObjectDisposedException ex)
  20. {
  21. Console.WriteLine(ex.Message + "对象已被释放");
  22. }
  23. catch (InvalidOperationException ex)
  24. {
  25. Console.WriteLine(ex.Message + "已标记为已完成添加操作或队列未接收该项");
  26. }
  27. }
  28. public object Dequeue()
  29. {
  30. object obj = null;
  31. try
  32. {
  33. obj = bQueue.Take();
  34. Console.WriteLine("出队后连接池个数:" + bQueue.Count);
  35. }
  36. catch (ObjectDisposedException ex)
  37. {
  38. Console.WriteLine(ex.Message + "对象已被释放");
  39. }
  40. catch (InvalidOperationException ex)
  41. {
  42. Console.WriteLine(ex.Message + "队列为空,无法获取");
  43. }
  44. return obj;
  45. }
  46. public bool Dequeue(out object item, int millisecondsTimeout)
  47. {
  48. bool flag = false;
  49. try
  50. {
  51. flag = bQueue.TryTake(out item, millisecondsTimeout);
  52. Console.WriteLine("出队后连接池个数超时:" + bQueue.Count);
  53. }
  54. catch (ObjectDisposedException ex)
  55. {
  56. Console.WriteLine(ex.Message + "对象已被释放,连接池为空");
  57. item = null;
  58. flag = false;
  59. }
  60. catch (ArgumentOutOfRangeException ex)
  61. {
  62. Console.WriteLine(ex.Message + "millisecondsTimeout为-1表无期限超时,不能为非-1的负数");
  63. item = null;
  64. flag = false;
  65. }
  66. return flag;
  67. }
  68. public int Count()
  69. {
  70. int counter = 0;
  71. try
  72. {
  73. counter = bQueue.Count();
  74. Console.WriteLine("调用Count方法后" + counter);
  75. }
  76. catch (ObjectDisposedException ex)
  77. {
  78. Console.WriteLine(ex.Message + "对象已被释放");
  79. }
  80. return counter;
  81. }
  82. }
  83. }