Solved

Stopping Windows Service programmatically

Posted on 2004-08-16
11
1,805 Views
Last Modified: 2012-06-27
Hi,

I have a windows service (c#) that I need to stop programmatically from within itself.

I know normally I can do something like this:


System.ServiceProcess.ServiceController mySC = new ServiceController(this.ServiceName);
if (mySC.CanStop)
{
      mySC.Stop();
}


However,  I need to be able to instruct the service to stop while it is still in the OnStart process - specifically, has a state of StartPending.

The service Im writing has a number of config files upon which it is absolutely dependant, and must stop regardless of what else its doing, should a file be missing or corrupt...

Cheers,
Stew
0
Comment
Question by:stewfidgeon
11 Comments
 
LVL 4

Expert Comment

by:Jigit
ID: 11808711
You can call OnStop from OnStart method:

protected override void OnStart(string[] args)
{
      OnStop();
}

HTH,
Jigit

0
 
LVL 1

Author Comment

by:stewfidgeon
ID: 11808844
Jigit,

Sorry, but that doesnt work.    The OnStop method doesnt get executed until the service enters the Running status (see the service controller status enumeration documentation).

Calling OnStop from OnStart doesnt do anything as the ServiceController CanStop attribute is still false, so the service simply ignores the Stop request.

I need to forcibly stop service execution from within the OnStart method itself...

Cheers,
Stew.

0
 
LVL 19

Expert Comment

by:Desp
ID: 11808919
0
 
LVL 1

Author Comment

by:stewfidgeon
ID: 11808970
Desp,

Sorry, but that wont work either.

The service state is StartPending, not running. I need to go directly from StartPending to Stopping the service, without ever reaching the Running state.

In the accepted answer for your link, the service has reached the Running state.

When a service has StartPending status, the CanStop attribute is false, so all stop / OnStop commands are ignored.... I need to overrule this and stop anyway....

Stew.
0
 
LVL 19

Expert Comment

by:Desp
ID: 11808999
This is not the answer but can you just check that these will work?

System.ServiceProcess.ServiceController myController =   new System.ServiceProcess.ServiceController("Your Service name");
myController.Stop();
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 1

Author Comment

by:stewfidgeon
ID: 11809137
Desp,

I already did that before posting the question.  That code snippet is included in my original post.

Ive tried it again, and as you'd expect, it still doesnt work...

Stew
0
 
LVL 19

Accepted Solution

by:
Desp earned 500 total points
ID: 11809209
just find out that  yu can't stop your service from within its handlers (OnStart etc.).  you can use a Timer put  ServiceController code stop your service in its clicked/elapsed event..
 
[source]
http://www.dotnet247.com/247reference/msgs/32/161202.aspx
0
 
LVL 1

Author Comment

by:stewfidgeon
ID: 11809498
Yeah, I've already added one of those.

The problem with that as a solution is that the timer would fire regularly checking the status of the error code and deciding if it should stop the service.

Its also somewhat more 'lashy' than I'm looking for here....  (Current employer is a large bank...)

What I'd really like to find is some part of the .net framework that can exercise absolute power over a service and shut it down immediately....


In the absence of any decent suggestions by the end of the day, I'll give the points to Desp for effort....
0
 
LVL 37

Expert Comment

by:gregoryyoung
ID: 11810419
if its stuck in startpending you probably have a coding problem with the service itself ... if not try killing the owned process directly (if you have permissions).
0
 
LVL 1

Author Comment

by:stewfidgeon
ID: 11810811
gregoryyoung

My service isnt stuck, as such. Im trying to handle a situation where a config file is missing or corrupt.  The config file is absolutely required by the service and if it isnt there, I want to terminate the service (stop it).

The work around Im using is very similar to Desp's suggestion above.

I set the value of an internal variable to true if theres been an error. I have a timer (which wont start counting until the service is running - ie it reaches the Running state) that check this and stops the service if theres been an error.

The first time the service executes its operations normally, I kill the timer.


What the service does is monitor the file system waiting for a file to be created in a specific directory, with a specific extension (from the config file). This file is opened, and a set of ftp commands read from it.   These then get passed into an FTP object Ive knocked up.

If the config file isnt present, the service logs an error, and then stops.    That being the tricky bit.   Theres no way to overrule the ServiceController.CanStop property, and if that property isnt True, you cant stop the service - short of finding its PID and killing it yourself.... a bit more drastic than I'd intended.

The CanStop property is set by the ServiceController.Status property, and requires a status of Running.... which the service cant reach until after it Starts (completes the StartPending status)....   which was the problem...



Thanks to everyone that helped....   M$, if you ever read this, the ability to stop a service starting due to programmable conditions would be a nice enhancement!!
0
 

Expert Comment

by:ralphad
ID: 11890726
I think you are doing something wrong conceptually.

A service, in it's normal operational state, should be running.

Any errors, due to config, etc. should be logged and appropriate actions be taken on inspection of those logs.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now