C# Windows 服务可以自行停止吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11770206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:10:18  来源:igfitidea点击:

Can a Windows service stop itself?

c#windowswindows-services

提问by user1077127

I have a Windows service whose startup type is automatic, but I want to do some checks when the service starts, and have the service stop automatically if these checks fail.

我有一个 Windows 服务,它的启动类型是自动的,但是我想在服务启动时做一些检查,如果这些检查失败,让服务自动停止。

How can I do this? My service is written in C#.

我怎样才能做到这一点?我的服务是用 C# 编写的。

回答by Eugene

You can use ServiceControllerand call .stop.

您可以使用ServiceController并调用 .stop。

ServiceController sc= new ServiceController(service);
sc.Stop();

回答by Simon M?Kenzie

You can call the Stopmethod on your ServiceBaseclass. See msdnfor more details.

您可以StopServiceBase类上调用该方法。有关更多详细信息,请参阅msdn