我如何可以验证,如果Windows服务运行 [英] How can I verify if a Windows Service is running

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

问题描述

我在C#(嵌入式XP上运行2.0)的应用程序与该被作为Windows服务中实现的看门狗通信。当设备启动,该服务通常需要一定的时间来启动。我想检查一下,从我的code,如果服务正在运行。我怎样才能做到这一点?


解决方案

我想这样的事情会的工作:

添加System.ServiceProcess到项目引用(这是.NET选项卡上)。

 使用System.ServiceProcess;ServiceController的SC =新的ServiceController(SERVICENAME);开关(sc.Status)
{
    案例ServiceControllerStatus.Running:
        返回运行;
    案例ServiceControllerStatus.Stopped:
        返回停止;
    案例ServiceControllerStatus.Paused:
        返回已暂停;
    案例ServiceControllerStatus.StopPending:
        返回停止;
    案例ServiceControllerStatus.StartPending:
        返回启动
    默认:
        返回状态更改
}

编辑:还有一种方法 sc.WaitforStatus(),需要一个期望的状态和超时,从来没有使用过它,但它可能会满足您的需求。

编辑:一旦你得到了状态,再次获得状态,您将需要调用 sc.Refresh()第一

参考:<一href=\"http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller%28VS.80%29.aspx\">ServiceController在对象.NET。

I have an application in C# (2.0 running on XP embedded) that is communicating with a 'watchdog' that is implemented as a Windows Service. When the device boots, this service typically takes some time to start. I'd like to check, from my code, if the service is running. How can I accomplish this?

解决方案

I guess something like this would work:

Add System.ServiceProcess to your project references (It's on the .NET tab).

using System.ServiceProcess;

ServiceController sc = new ServiceController(SERVICENAME);

switch (sc.Status)
{
    case ServiceControllerStatus.Running:
        return "Running";
    case ServiceControllerStatus.Stopped:
        return "Stopped";
    case ServiceControllerStatus.Paused:
        return "Paused";
    case ServiceControllerStatus.StopPending:
        return "Stopping";
    case ServiceControllerStatus.StartPending:
        return "Starting";
    default:
        return "Status Changing";
}

Edit: There is also a method sc.WaitforStatus() that takes a desired status and a timeout, never used it but it may suit your needs.

Edit: Once you get the status, to get the status again you will need to call sc.Refresh() first.

Reference: ServiceController object in .NET.

这篇关于我如何可以验证,如果Windows服务运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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