How to stop a Windows Service from within itself?

  • Thread starter Jacobus Terhorst
  • 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
 
J

John Timney \(ASP.NET MVP\)

Throw an unhandled exception and your service should stop.

--
Regards

John Timney
ASP.NET MVP
Microsoft Regional Director
 
J

Jacobus Terhorst

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...
 
J

Jacobus Terhorst

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...
 
J

Jared Parsons [MSFT]

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.
 
J

John Timney \(ASP.NET MVP\)

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top