以编程方式启动Windows Service [英] Start Windows Service programmatically

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

问题描述

我正在创建的应用程序遇到问题。我正在尝试通过C#应用程序启动Windows服务。当我单击开始按钮时,似乎一切正常,但是当我登录到服务器时,该服务仍未显示其正在运行。但是,第二次运行它时,出现一个异常,指出该服务的实例已在运行。再次登录服务器时,该服务似乎已停止。

I am having an issue with an application that I am creating. I am trying to start a windows service through my C# app. When I click my start button, it looks like everything goes through but when I log into the server, the service still does not show that it is running. However, the second time I run it, I get an exception that says the instance of the service is already running. Again when I log into the server, the service appears to be stopped. Has anyone ever seen this?

这是我的代码。

try
{
    while (reader.Read())
    {
        int timeoutMilliseconds = 1000;
        string serviceName = reader["ServiceName"].ToString();
        string permission = reader["Permission"].ToString();

        if (permission == "E")
        {
            lblServStartSuccess.Visible = true;

            ServiceController service = new ServiceController(serviceName);
            TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running, timeout);
        }
        else
        {
            lblServErrorStart.Visible = true;
        }
    }
}
catch (Exception ex)
{
    Response.Write(ex.ToString());
}

编辑:这是我收到的例外一种服务:

Here is the exception I received on one service:


System.InvalidOperationException:在计算机。上找不到服务逻辑磁盘管理器
管理服务。 --->
System.ComponentModel.Win32Exception:指定的服务不存在作为已安装服务的
---内部异常堆栈跟踪结束

System.InvalidOperationException: Service Logical Disk Manager Administrative Service was not found on computer '.'. ---> System.ComponentModel.Win32Exception: The specified service does not exist as an installed service --- End of inner exception stack trace

我知道该服务存在。我是否需要在服务之前添加一些内容来告诉它要看什么服务器?

I know the service exists. Do I need to add something in front of the service to tell it what server to look at?

推荐答案

如果您显示的代码在与应该在其上运行服务的机器不同的机器上执行(我是否从您的注释中看不出是否是这种情况),则需要在ServiceController构造器中提供机器名称。

If the code you showed is executing on a different machine than where the service is supposed to run (I'm not clear from your comments if that's the case or not), you would need to provide the machine name in the ServiceController constructer.

是否可以成功启动服务,但不能在您认为的机器上启动?

Is it possible you are successfully starting the service, but not on the machine you think? That would fit the symptoms you describe.

ServiceController service = new ServiceController(serviceName, serverName);

也请参见 ServiceController 构造函数文档

Also see ServiceController constructor documentation.

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

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