How to stop Windows service programmatically

The Stop-function sends a stop-signal. It does not wait till the signal is received and processed.

You will have to wait till the Stop-signal has done it’s work. You can do that by calling WaitForStatus:

service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped);

See for more info: http://msdn.microsoft.com/nl-nl/library/system.serviceprocess.servicecontroller.waitforstatus(v=vs.71).aspx

Environment.Exit is a nasty one. DO NOT USE IT! It aborts your application the hard way, without performing any cleanup in finally blocks, without calling finalizer methods by the GC, it terminates all other forground threads, etc. I can imagine that your application is aborted before the stop-signal even left your application.

Leave a Comment