WaitHandleArray.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System;
  2. using System.Threading;
  3. namespace SmartCoalApplication.SystemLayer
  4. {
  5. public sealed class WaitHandleArray
  6. {
  7. private WaitHandle[] waitHandles;
  8. private IntPtr[] nativeHandles;
  9. /// <summary>
  10. /// The minimum value that may be passed to the constructor for initialization.
  11. /// </summary>
  12. public const int MinimumCount = 1;
  13. /// <summary>
  14. /// The maximum value that may be passed to the construct for initialization.
  15. /// </summary>
  16. public const int MaximumCount = 64; // WaitForMultipleObjects() can only wait on up to 64 objects at once
  17. /// <summary>
  18. /// Gets or sets the WaitHandle at the specified index.
  19. /// </summary>
  20. public WaitHandle this[int index]
  21. {
  22. get
  23. {
  24. return this.waitHandles[index];
  25. }
  26. set
  27. {
  28. this.waitHandles[index] = value;
  29. this.nativeHandles[index] = value.SafeWaitHandle.DangerousGetHandle();
  30. }
  31. }
  32. /// <summary>
  33. /// Gets the length of the array.
  34. /// </summary>
  35. public int Length
  36. {
  37. get
  38. {
  39. return this.waitHandles.Length;
  40. }
  41. }
  42. /// <summary>
  43. /// Initializes a new instance of the WaitHandleArray class.
  44. /// </summary>
  45. /// <param name="count">The size of the array.</param>
  46. public WaitHandleArray(int count)
  47. {
  48. if (count < 1 || count > 64)
  49. {
  50. throw new ArgumentOutOfRangeException("count", "must be between 1 and 64, inclusive");
  51. }
  52. this.waitHandles = new WaitHandle[count];
  53. this.nativeHandles = new IntPtr[count];
  54. }
  55. private uint WaitForAll(uint dwTimeout)
  56. {
  57. return SafeNativeMethods.WaitForMultipleObjects(this.nativeHandles, true, dwTimeout);
  58. }
  59. /// <summary>
  60. /// Waits for all of the WaitHandles to be signaled.
  61. /// </summary>
  62. public void WaitAll()
  63. {
  64. WaitForAll(NativeConstants.INFINITE);
  65. }
  66. public bool AreAllSignaled()
  67. {
  68. return AreAllSignaled(0);
  69. }
  70. public bool AreAllSignaled(uint msTimeout)
  71. {
  72. uint result = WaitForAll(msTimeout);
  73. if (result >= NativeConstants.WAIT_OBJECT_0 && result < NativeConstants.WAIT_OBJECT_0 + this.Length)
  74. {
  75. return true;
  76. }
  77. else
  78. {
  79. return false;
  80. }
  81. }
  82. public int WaitAny()
  83. {
  84. int returnVal = (int)SafeNativeMethods.WaitForMultipleObjects(this.nativeHandles, false, NativeConstants.INFINITE);
  85. return returnVal;
  86. }
  87. }
  88. }