Solved

Stopping Windows Service programmatically

Posted on 2004-08-16
11
1,780 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
Comment Utility
You can call OnStop from OnStart method:

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

HTH,
Jigit

0
 
LVL 1

Author Comment

by:stewfidgeon
Comment Utility
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
Comment Utility
0
 
LVL 1

Author Comment

by:stewfidgeon
Comment Utility
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
Comment Utility
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 1

Author Comment

by:stewfidgeon
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

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…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

743 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

15 Experts available now in Live!

Get 1:1 Help Now