ThreadPoolHelper.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace ProjectBase.Data.Threading
  8. {
  9. /// <summary>
  10. /// 线程池辅助操作类
  11. /// </summary>
  12. public class ThreadPoolHelper
  13. {
  14. /// <summary>
  15. /// 方法委托
  16. /// </summary>
  17. public delegate void WaitCallbackNew();
  18. /// <summary>
  19. /// (集合)通知等待线程,事件已经发生。这个类不能被继承。
  20. /// </summary>
  21. private static List<WaitHandle> AutoResetEvents;
  22. /// <summary>
  23. /// 线程池的实际WaitCallback委托对象。
  24. /// </summary>
  25. /// <param name="state"></param>
  26. static void Callback(object state)
  27. {
  28. WaitCallbackHelper wcbh = (state as WaitCallbackHelper);
  29. wcbh.Callback();
  30. (wcbh.WaitHandle as AutoResetEvent).Set();
  31. }
  32. /// <summary>
  33. /// 把执行方法放到队列中。
  34. /// 当线程池线程变为可用的时候,方法执行。
  35. /// </summary>
  36. /// <param name="callback">委托对象</param>
  37. public static bool QueueUserWorkItem(WaitCallbackNew callback)
  38. {
  39. WaitCallbackHelper wcbh = new WaitCallbackHelper();
  40. wcbh.Callback = callback;
  41. wcbh.WaitHandle = new AutoResetEvent(false);
  42. if (AutoResetEvents == null)
  43. {
  44. AutoResetEvents = new List<WaitHandle>();
  45. }
  46. AutoResetEvents.Add(wcbh.WaitHandle);
  47. return ThreadPool.QueueUserWorkItem(new WaitCallback(Callback), wcbh);
  48. }
  49. /// <summary>
  50. /// 把执行方法放到队列中。
  51. /// 当线程池线程变为可用的时候,方法执行。
  52. /// </summary>
  53. /// <param name="proc">委托对象数组</param>
  54. /// <returns></returns>
  55. public static bool QueueUserWorkItems(params WaitCallbackNew[] proc)
  56. {
  57. bool result = true;
  58. foreach (WaitCallbackNew tp in proc)
  59. {
  60. result &= QueueUserWorkItem(tp);
  61. }
  62. return result;
  63. }
  64. /// <summary>
  65. ///等待指定数组中所有元素收到信号
  66. /// </summary>
  67. public static bool WaitAll()
  68. {
  69. return WaitHandle.WaitAll(AutoResetEvents.ToArray());
  70. }
  71. /// <summary>
  72. ///等待指定数组中任何一个元素收到信号
  73. /// </summary>
  74. /// <returns>满足等待的对象数组索引</returns>
  75. public static int WaitAny()
  76. {
  77. return WaitHandle.WaitAny(AutoResetEvents.ToArray());
  78. }
  79. /// <summary>
  80. /// 一个回调一个WaitHandle容器
  81. /// </summary>
  82. class WaitCallbackHelper
  83. {
  84. public WaitCallbackNew Callback
  85. {
  86. get;
  87. set;
  88. }
  89. public WaitHandle WaitHandle
  90. {
  91. get;
  92. set;
  93. }
  94. }
  95. }
  96. }