Stop Windows service in code

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have created a windows service but am having difficulties handling
exceptions in the OnStart.

What I want to do is if an exeception occurs during any of the code executed
during the OnStart is to log the problem and stop the service.

I've already sorted out the logging of the problem to the event log but the
suggested solution I have implemented for stopping the service does not work.
Currently I declare a ServiceController and set it to the service and then
instruct it to stop but this doesn't work (code snippet below), all that
happens is that the service shows as 'Starting' in the services list.

Anybody have any ideas?

Nathan

Code:

try
'Initalisation code here
Catch ex As Exception
EventLogger.WriteEntry("Error attempting to start Service,
EventLogEntryType.Error)
Dim scm As New ServiceController(Me.ServiceName)
scm.Stop()
End try
 
Nathan,
Have you tried:
try
'Initalisation code here
Catch ex As Exception
EventLogger.WriteEntry("Error attempting to start Service,
EventLogEntryType.Error) Throw
End try

Which causes the OnStart itself to fail, letting the framework & SCM know
that the service is not able to start. Instead of the "Service started
successfully" message, you will get a "Service cannot be started" message
along with ex.ToString info.
What I want to do is if an exception occurs during any of the code
executed
during the OnStart is to log the problem and stop the service.
As the above shows, the framework already does this for you. At least in
..NET 1.1 SP1.


I normally use ServiceController to control the service from other programs,
not the service itself...

Hope this helps
Jay
 
Back
Top