简体   繁体   中英

How do I quit a Windows service from inside the service?

I have a Windows Service. On startup it checks whether any work has been assigned to it - and if none has, it just quits. The problem is that the recovery mechanism is set to Restart the Service.

在此处输入图片说明

This is what I want if the service legitimately crashes, but not if I quit the service programmatically on my own.

So far everything I've tried below has resulted in Windows automatically restarting the service:

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

private void StartMyService()
{
    if (WorkAvailable()) {
      InitWork();
    } else {
      this.ExitCode = 0;  // no errors
      Stop();
    }
}

protected override void OnStop()
{
    // dispose of things

    try
    {
        if (th != null && th.ThreadState == ThreadState.Running)
            th.Abort();
    }
    catch { }

    Environment.Exit(this.ExitCode);
}

I've tried different ExitCode values, but Windows always restarts the Service. I've also tried Environment.FailFast with same results. What am I missing?

Ignoring the issue of whether or not this is good design, the reason the OS is using the failure recovery action is because the service is failing.

When you call Stop the runtime marks the service as being in the process of stopping. It then calls the OnStop method. When the OnStop method returns it finishes cleanup and then exits the service. If this is the only service in the executable then the executable also exits. There is never a need to exit the process yourself.

When you call Environment.Exit (or Environment.FailFast) you cause the service executable to suddenly exit while the ServiceControlManager still has it listed as running, so the OS quite rightly considers the service to have failed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM