Darey
Darey

Reputation: 497

c# Unable to stop windows service

I have a Windows service which triggers a thread on OnStart(string[] args). There are other threads created by this main thread. After installing and starting the service, when I try to stop the service I am unable to stop the service during the first attempt. When I right click on my service and request 'Stop'. I get the below exception and the service is still running.

Windows could not stop the service on Local Computer. The service did not return error. This could be an internal windows error or an internal service error. If the problem persists, contact your system administrator.

When I try to stop it again, I end up with other message as

Windows could not stop the service on Local computer.
Error 1061: The service cannot accept control messages at this time.

but service is stopped. So I am performing right click -> Stop, twice to stop a service.

I tried to abort thread and stop the service as below but no gain.

protected override void OnStop()
{
    onStartThread.Abort();
    Log.AuditEventLogger("Service Stopped");
    this.Stop();
}

I highly appreciate any suggestions. Thank you.

Upvotes: 3

Views: 8835

Answers (3)

Ananke
Ananke

Reputation: 1230

Firstly, you are calling this.Stop which will then call your OnStop method again. You have an infinite loop so your service is not stopping.

Secondly, don't go aborting your threads like this. Signal for them to stop e.g. using a wait handle (ManualResetEvent) and join the thread. If you are using tasks then use a CancellationToken.

Upvotes: 3

Ricky
Ricky

Reputation: 2374

onStartThread.Abort(); 

Will not necessarily always abort the thread. When a call is made to the Abort method to destroy a thread, the common language runtime throws a ThreadAbortException. There is no guarantee that the thread will ever end. If you want to wait until the aborted thread has ended, you can call the Thread.Join method. Join is a blocking call that does not return until the thread actually stops executing.

Upvotes: 0

Daniel Kelley
Daniel Kelley

Reputation: 7737

Based on your code snippet in the comments I'd suggest making your thread a background thread. By default I believe it will be a foreground thread, and so if it is busy will stop your proecess terminating.

See MSDN for more detail.

However, as you haven't provided a great deal of detail in the question there may well be other factors in play too.

Upvotes: 0

Related Questions