简体   繁体   English

如何从线程停止 windows 服务应用程序?

[英]How do I stop a windows service application from a thread?

I have a windows service that starts a thread in the OnStart method.我有一个 windows 服务,它在 OnStart 方法中启动一个线程。

Basically I want to be able to stop the service if something goes really wrong (like an unhandled exception).基本上,如果出现问题(例如未处理的异常),我希望能够停止服务。

Currently I'm using ServiceBase.Stop() but that involves having a ServiceBase instance somewhere visible to the thread, which in turn involves having my instance be declared as public static in the main program.目前我正在使用ServiceBase.Stop()但这涉及在某个线程可见的某个地方有一个ServiceBase实例,这反过来又涉及在主程序中将我的实例声明为public static

Is there any "better way" to stop the service?有没有“更好的方法”来停止服务? If it isn't... is it safe to do it that way?如果不是……这样做安全吗?

The easiest and, in my opinion, cleanest way is to use a public static property of the service class.在我看来,最简单且最干净的方法是使用服务 class 的公共 static 属性。 The only time this won't work is if you are using the same service class to run multiple services in the same process, something that is very rare.唯一不起作用的情况是,如果您使用相同的服务 class 在同一进程中运行多个服务,这种情况非常罕见。

private static MyService m_ServiceInstance;

public static MyService ServiceInstance
{
    get { return m_ServiceInstance; }
}

public MyService()
{
    InitializeComponents();
    //Other initialization
    m_ServiceInstance = this;
}

Injecting the service instance into every method that could possibly need it is an alternative but it can quickly get messy and it has no real advantages over just using a static property.将服务实例注入每个可能需要它的方法是一种替代方法,但它很快就会变得混乱,并且与仅使用 static 属性相比,它没有真正的优势。

Check out the example here on how to use the ServiceController class to start and stop services.此处查看有关如何使用 ServiceController class 启动和停止服务的示例

Alternatively, you could pass your service instance to the thread when you create it (or set it as an instance variable in the thread class, etc.) without having to make your service class static.或者,您可以在创建服务实例时将其传递给线程(或将其设置为线程 class 等中的实例变量),而无需使您的服务为 class static。

A short example for completeness:完整性的简短示例:

ServiceController sc = new ServiceController("MyService");
sc.Stop();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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