Q: How can I create, set and wait on named system events from managed code?
The simplest way is to P/Invoke the win32 API calls.
private enum EventFlags { EVENT_PULSE = 1, EVENT_RESET = 2, EVENT_SET = 3 }
[DllImport("coredll.dll", EntryPoint="WaitForSingleObject", SetLastError = true)] private static extern int CEWaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
[DllImport("coredll.dll", EntryPoint="EventModify", SetLastError = true)] private static extern int CEEventModify(IntPtr hEvent, uint function);
[DllImport("coredll.dll", EntryPoint="CreateEvent", SetLastError = true)] private static extern IntPtr CECreateEvent(IntPtr lpEventAttributes, int bManualReset, int bInitialState, string lpName);
/// /// Create a system event (*not* a managed event) /// /// /// /// /// public static IntPtr CreateEvent(bool bManualReset, bool bInitialState, string lpName) { return CECreateEvent(IntPtr.Zero, Convert.ToInt32(bManualReset), Convert.ToInt32(bInitialState), lpName); }
/// /// This function sets the state of the specified event object to signaled /// /// /// public static bool SetEvent(IntPtr hEvent) { return Convert.ToBoolean(CEEventModify(hEvent, (uint)EventFlags.EVENT_SET)); }
/// /// This function sets the state of the specified event object to nonsignaled /// /// /// public static bool ResetEvent(IntPtr hEvent) { return Convert.ToBoolean(CEEventModify(hEvent, (uint)EventFlags.EVENT_RESET)); }
/// /// This function provides a single operation that sets (to signaled) the state of the specified event object and then resets it (to nonsignaled) after releasing the appropriate number of waiting threads /// /// /// public static bool PulseEvent(IntPtr hEvent) { return Convert.ToBoolean(CEEventModify(hEvent, (uint)EventFlags.EVENT_PULSE)); }
/// /// This function returns when the specified object is in the signaled state or when the time-out interval elapses /// /// /// /// public static int WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds) { return CEWaitForSingleObject(hHandle, dwMilliseconds); }
|