Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EventWaitHandle not getting closed on process kill

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?

like image 255
Zulakis Avatar asked Dec 31 '25 05:12

Zulakis


1 Answers

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

like image 190
Hans Passant Avatar answered Jan 02 '26 17:01

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!