3

My windows service is creating 1 thread in OnStart() method. The code of thread contains 1 while loop and looks like this:

    Thread mworker;       
    AutoResetEvent mStop = new AutoResetEvent(false); 
     protected override void OnStart(string[] args)
{
    // TODO: Add code here to start your service.

    mworker = new Thread(pwd_fetch);
    mworker.IsBackground = false;
    mworker.Start();
}

protected override void OnStop()
{
    // TODO: Add code here to perform any tear-down necessary to stop your service.
    mStop.Set();
    mworker.Join();
}

private void pwd_fetch()
{
    while(true)
    {
        //some other code

        if (mStop.Set()==true)
            break;
    }
}

I want while loop condition as true, but to break the loop I'm using if() instruction, but still unable to stop service.

Anybody know, why this is so? How can I solve this problem?

2

5 Answers 5

2

To stop the service you have to call the servicecontroller instance and stop it

ServiceController service = new ServiceController("ServiceName");
service .Stop();
2

In your thread loop method, you need to use the mStop.WaitOne (with a timeout). Calling set will set the handle... that's not what you want to do here.

 if (mStop.WaitOne(500))
     break;
3
  • I'd suggest attaching the visual studio debugger to your running service. Set breakpoints in the OnStop() and pwd_fetch() routines to see what's going on. Try to stop the service and see what breakpoints are hit and what is happening. This should do the trick.
    – pilotcam
    Jun 28, 2012 at 10:30
  • after mStop.Set() instruction breakpoint comes to mworker.join(). breakpoint never goes into pwd_fetch()
    – sailer
    Jun 28, 2012 at 10:44
  • Just a guess: Perhaps something else is resetting your mStop? It is an AutoResetEvent.. any Wait (or Reset) would do it and prevent your loop from exiting. In this case, a manual reset event might be a safer bet. Other than that, I can only suggest to keep stepping through your thread loop with the debugger and see what's being hit.
    – pilotcam
    Jun 28, 2012 at 11:15
0

If you want the service to stop itself, you can simply call:

this.Stop()
0

1.Use a boolean variable instead of "true" always in while loop Then you can set it to false where you need to terminate the codes inside the loop.

2.Call mworker.Abort() to stop the thread.

3.Stop service by

new ServiceController("ServiceName").Stop();

0

You have to add your thread code in the service started event, and not on starting.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.