Solved

Stopping Windows Service programmatically

Posted on 2004-08-16
11
1,860 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

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

Enroll in May's Course of the Month

May’s Course of the Month is now available! Experts Exchange’s Premium Members and Team Accounts have access to a complimentary course each month as part of their membership—an extra way to increase training and boost professional development.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
how to remove duplicate code from my project 5 66
Coding for the first time 9 99
orderby list (from Json) 1 43
C# Windows Form Navigation - Total Beginner 9 92
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…
Suggested Courses

734 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