How to stop a Windows Service from within itself?

  • Thread starter Thread starter Jacobus Terhorst
  • Start date Start date
J

Jacobus Terhorst

Using C#:

I tried:
ServiceController me = new ServiceController(this.ServiceName);
me.Stop();

it raises an exception: Cannot find Service


I also tried:

Process.Start("net.exe", "stop " + this.ServiceName);


That did work either.


from DOS:
net stop ServiveName
works.

Any suggestions welcome.

Jacobus Terhorst
 
Throw an unhandled exception and your service should stop.

--
Regards

John Timney
ASP.NET MVP
Microsoft Regional Director
 
I tried it, but no cigar.

I am starting a timer in the OnStart method

and the worker code is started from the timer event.

Wherever I throw an unhandled exception, the service is not stopped...
 
It does work from the OnStart method...


Jacobus Terhorst said:
I tried it, but no cigar.

I am starting a timer in the OnStart method

and the worker code is started from the timer event.

Wherever I throw an unhandled exception, the service is not stopped...
 
Where are you trying to stop the service from? I don't think that you can
stop it from the initialization or start method in the way that you are
describing.
 
Have you tried a simple Application.Exit()

You might have to call exitthread before calling exit.

The service itself must have the CanStop property set to true when your
developing the service. You can check if you can stop it with .......
if (myController.CanStop)
{
myController.Stop();
}
The suggestion to throw an exception is a complete hack that another MVP
suggested worked. The reason it works in onStart is that the service has
not yet started.

Your alternative would be to overide the DACL for the service, allocating a
new security descriptor and then using a call to advapi32 to get a better
control at the API level. It still might not work, as the user account your
service runs under has to have service stop permissions so check which
account yout running the service under.

-- Regards

John Timney
ASP.NET MVP
Microsoft Regional Director
 
Back
Top