如何停止Windows服务programmaticaly [英] How to stop Windows service programmaticaly

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

问题描述

美好的一天!

我有一个关于编程的Windows服务的问题:如何停止我的Windows服务

I have a question about programming Windows services: how to stop my windows service?

下面是一个很简单的例子code(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!

如何从主停止我的service()方法?

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

推荐答案

停止 - 函数发送停止信号。它不等到信号被接收和处理。

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);

详情参见:<一href="http://msdn.microsoft.com/nl-nl/library/system.serviceprocess.servicecontroller.waitforstatus(v=vs.71).aspx" rel="nofollow">http://msdn.microsoft.com/nl-nl/library/system.serviceprocess.servicecontroller.waitforstatus(v=vs.71).aspx

Environment.Exit 是一个讨厌的。不要使用它!它中止应用程序的硬盘的方式,在没有finally块进行任何清理,而不调用释放方法由GC,它终止所有其他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服务programmaticaly的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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