I am creating a Windows service that works hand in hand with other applications. These applications start communication with the service VIA Remoting. Once the connection has been made, I want to applications to stop communication immediately if the service is stopped. Meaning I don't want to wait for a Timer to elapse or have an exception because the communication was trying to use IpcConnection that is no longer valid.
This all works when the service is running Interactively instead of as a service. When it runs as a service then I get an exception. The service runs as Admin whether it is ran as a service or Interactively. If I run the other application as Admin, then it works as expected. Unfortunately, running this application as Admin will not be an option in production.
I've narrowed it down to what is causing the exception.
var serverProc = Process.GetProcessById(_remote.ProcessId);
serverProc.WaitForExit();
serverProc
is successful, but WaitForExit
fails.
System.ComponentModel.Win32Exception (0x80004005): Access is denied
at System.Diagnostics.ProcessManager.OpenProcess(Int32 processId, Int32 access, Boolean throwIfExited)
at System.Diagnostics.Process.GetProcessHandle(Int32 access, Boolean throwIfExited)
at System.Diagnostics.Process.WaitForExit(Int32 milliseconds)
I can substitute this code with a Timer
, but I was hoping this current technique would work.
Am I doing something work and is there something I can do to avoid the exception and use similar code?