3
votes

I got a C# program which opens a EventWaitHandle like this to get triggered by a Windows Service.

EventWaitHandle sampleEventHandle = new EventWaitHandle(false, EventResetMode.AutoReset, "Global\\sampleEvent");

When the program now gets killed (or dies due to a unexpected error), the EventWaitHandle is not being closed and when restarting the program the following error occurs:

System.UnauthorizedAccessException: Access to the path is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.Threading.EventWaitHandle..ctor(Boolean initialState, EventResetMode mode, String name)

After a minute, the EventWaitHandle is getting closed and you can restart the Application.

Any ideas how to fix this issue?

1
Thanks. I think this will fix my issue. Do you know what the default EventWaitHandleSecurity is? (Just out of interest, i would like to know) - Zulakis
Would still be interesting to know how to automatically close the EventWaitHandle on process kill... - Zulakis
I don't. Just did a quick Google search and the experiment didn't look like something I could immediately accomplish (but the linked looked promising for you). Was planning on checking this if I had time later. - Austin Salonen

1 Answers

2
votes

This happens because the service has a handle opened on the same object. Which is to be expected, after all you are using this to implement signaling between the service and your program. The physical underlying Windows named object doesn't get removed from global namespace until the last handle is closed.

So getting an exception on this gives you a real problem diagnostic, the service is using the wrong handle and can never communicate with you when you restart your program. How this gets resolved after a minute is hard to guess, I have to assume that the service periodically calls OpenExisting().

The solution is simple: it should be the service that creates the wait handle and your UI program should call OpenExisting(). The event now always exists, at least as long as the service is alive. And it if doesn't then OpenExisting() gives you an excellent diagnostic of that with a WaitHandleCannotBeOpenedException