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

查看:34
本文介绍了如何以编程方式停止 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.

您必须等到停止信号完成它的工作.您可以通过调用 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

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

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天全站免登陆