[英]How do I quit a Windows service from inside the service?
I have a Windows Service. 我有Windows服务。 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: 到目前为止,我在下面尝试过的所有操作都导致Windows自动重新启动该服务:
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. 我尝试了不同的ExitCode值,但Windows总是重新启动服务。 I've also tried
Environment.FailFast
with same results. 我也尝试过
Environment.FailFast
,结果相同。 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. 当您调用Stop时,运行时会将服务标记为正在停止。 It then calls the OnStop method.
然后,它调用OnStop方法。 When the OnStop method returns it finishes cleanup and then exits the service.
当OnStop方法返回时,它将完成清理,然后退出服务。 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. 当您调用Environment.Exit(或Environment.FailFast)时,会导致服务可执行文件突然退出,而ServiceControlManager仍将其列出为正在运行,因此操作系统非常正确地认为该服务已失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.