如何以编程方式停止Windows服务 [英] How to stop Windows service programmatically

查看:99
本文介绍了如何以编程方式停止Windows服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于对Windows服务进行编程:如何停止我的Windows服务?

About programming Windows services: how to stop my windows service?

这是一个非常简化的示例代码(C#):

Here is a very simplified example code(C#):

// Here is my service class (MyTestService.cs).
public class MyTestService:ServiceBase{

    // Constructor.
    public MyTestService(){
         this.ServiceName = "My Test Service";
         return;
    }
};

//  My application class (ApplicationClass.cs).
public static class ApplicationClass{

    // Here is main Main() method.
    public static void Main(){
        // 1. Creating a service instance
        // and running it using ServiceBase.
        MyTestService service = new MyTestService();
        ServiceBase.Run(service);
        // 2. Performing a test shutdown of a service.
        service.Stop();
        Environment.Exit(0);
        return;
    };
};

所以:我刚刚创建了我的测试服务,就启动并停止了它。但是,当我查看Services.msc时,我的测试服务将继续运行,并且仅在单击停止链接后才停止。为什么? -为什么 service.Stop()命令什么都不做?

So: I've just created "My Test Service" started it and stopped. But when I'm looking into my Services.msc - "My Test Service" is continues to running and stops ONLY when I click a "Stop" link. Why? - why service.Stop() command does nothing?

ServiceController.Stop()也什么都不做!

ServiceController.Stop() also does nothing!

如何从Main()方法停止服务?

How can I stop my service from Main() method?

推荐答案

Stop 函数发送一个停止信号。它不会等到信号被接收和处理。

The Stop-function sends a stop-signal. It does not wait till the signal is received and processed.

您将必须等到Stop-signal完成工作。您可以通过调用 WaitForStatus 来做到这一点:

You will have to wait till the Stop-signal has done it's work. You can do that by calling WaitForStatus:

service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped);

有关更多信息,请参见: http://msdn.microsoft.com/nl-nl/library/system.serviceprocess.servicecontroller.waitforstatus(v = vs .71).aspx

See for more info: http://msdn.microsoft.com/nl-nl/library/system.serviceprocess.servicecontroller.waitforstatus(v=vs.71).aspx

Environment.Exit 是一个令人讨厌的环境。不要使用它!它以艰难的方式中止了您的应用程序,没有在finally块中执行任何清理,没有通过GC调用finalizer方法,它终止了所有其他forground线程,等等。我可以想象您的应用程序在停止信号甚至离开您的应用程序之前就被中止了。

Environment.Exit is a nasty one. DO NOT USE IT! It aborts your application the hard way, without performing any cleanup in finally blocks, without calling finalizer methods by the GC, it terminates all other forground threads, etc. I can imagine that your application is aborted before the stop-signal even left your application.

这篇关于如何以编程方式停止Windows服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆