EventWaitHandleFactory.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System.Threading;
  2. #if (_WINDOWS_CE)
  3. using System;
  4. using System.Runtime.InteropServices;
  5. #endif
  6. namespace Amib.Threading.Internal
  7. {
  8. /// <summary>
  9. /// EventWaitHandleFactory class.
  10. /// This is a static class that creates AutoResetEvent and ManualResetEvent objects.
  11. /// In WindowCE the WaitForMultipleObjects API fails to use the Handle property
  12. /// of XxxResetEvent. It can use only handles that were created by the CreateEvent API.
  13. /// Consequently this class creates the needed XxxResetEvent and replaces the handle if
  14. /// it's a WindowsCE OS.
  15. /// </summary>
  16. public static class EventWaitHandleFactory
  17. {
  18. /// <summary>
  19. /// Create a new AutoResetEvent object
  20. /// </summary>
  21. /// <returns>Return a new AutoResetEvent object</returns>
  22. public static AutoResetEvent CreateAutoResetEvent()
  23. {
  24. AutoResetEvent waitHandle = new AutoResetEvent(false);
  25. #if (_WINDOWS_CE)
  26. ReplaceEventHandle(waitHandle, false, false);
  27. #endif
  28. return waitHandle;
  29. }
  30. /// <summary>
  31. /// Create a new ManualResetEvent object
  32. /// </summary>
  33. /// <returns>Return a new ManualResetEvent object</returns>
  34. public static ManualResetEvent CreateManualResetEvent(bool initialState)
  35. {
  36. ManualResetEvent waitHandle = new ManualResetEvent(initialState);
  37. #if (_WINDOWS_CE)
  38. ReplaceEventHandle(waitHandle, true, initialState);
  39. #endif
  40. return waitHandle;
  41. }
  42. #if (_WINDOWS_CE)
  43. /// <summary>
  44. /// Replace the event handle
  45. /// </summary>
  46. /// <param name="waitHandle">The WaitHandle object which its handle needs to be replaced.</param>
  47. /// <param name="manualReset">Indicates if the event is a ManualResetEvent (true) or an AutoResetEvent (false)</param>
  48. /// <param name="initialState">The initial state of the event</param>
  49. private static void ReplaceEventHandle(WaitHandle waitHandle, bool manualReset, bool initialState)
  50. {
  51. // Store the old handle
  52. IntPtr oldHandle = waitHandle.Handle;
  53. // Create a new event
  54. IntPtr newHandle = CreateEvent(IntPtr.Zero, manualReset, initialState, null);
  55. // Replace the old event with the new event
  56. waitHandle.Handle = newHandle;
  57. // Close the old event
  58. CloseHandle (oldHandle);
  59. }
  60. [DllImport("coredll.dll", SetLastError = true)]
  61. public static extern IntPtr CreateEvent(IntPtr lpEventAttributes, bool bManualReset, bool bInitialState, string lpName);
  62. //Handle
  63. [DllImport("coredll.dll", SetLastError = true)]
  64. public static extern bool CloseHandle(IntPtr hObject);
  65. #endif
  66. }
  67. }