My service won't stop???

  • Thread starter Thread starter Peter Steele
  • Start date Start date
P

Peter Steele

Okay, I assume I'm missing something obvious here. I have created a simple
service in C# that on starting spawns a thread to do some processing. The
service can be stopped with a "net stop" command of course, but under some
circumstances the service will decide to terminate itself. My OnStart looks
something like this:

protected override void OnStart(string[] args)
{
serviceThread = new Thread(new ThreadStart(ServiceThreadStart));
serviceThread .Start();
}

So this is simple enough. The problem is that if I use "net stop ..." to
stop my service everything works fine. My thread detects the stop request
and shuts itself down, and the service itself then terminates. However, if
the service thread encounters some condition where it decides to shut itself
down, the service keeps on running. I assume I have to call some method to
tell the service control manager that the service is ending but I cannot
find what method I need to user. I even tried inserting an
Application.Exit() call in the service shutdown code and that didn't do the
trick. What do I need to call to get the service to terminate?
 
I just added the code

ServiceController sc = new ServiceController(this.ServiceName);
sc.Stop();

in my thread's shutdown logic and that did the trick. I don't think this is
the best way to do it though....
 
Back
Top