【问题标题】:(Re)Starting a Windows Service from out of my C# code does not work(重新)从我的 C# 代码中启动 Windows 服务不起作用
【发布时间】:2014-05-26 14:35:55
【问题描述】:

为了更新我自己编写的 Windows 服务,我编写了一个 C# 程序来停止该服务,复制新的 DLL,然后重新启动它。

我的第一个方法如下:

ServiceController service = new ServiceController(serviceName);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
// (...) copy the dll files
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);   

在停止服务工作时,启动方法产生以下错误:

Cannot start service FOVEA Service Debug on computer '.'.   
at System.ServiceProcess.ServiceController.Start(String[] args)    at
System.ServiceProcess.ServiceController.Start()

以管理员身份运行我的更新程序没有任何区别。

所以我尝试通过net start/stop service 在命令行中启动/停止服务,效果很好,我将 C# 程序更改为以下内容:

Process p = Process.Start("net", "stop \"" + serviceName + "\"");
p.WaitForExit();
p = Process.Start("net", "start \"" + serviceName + "\"");
p.WaitForExit(); 

像以前一样,停止服务是有效的。 net start service 的调用却被输出了

The service is not responding to the control function
more help is available by typing NET HELPMSG 2186

该服务是为本地登录用户(管理员)安装的,但我不明白为什么net start 可以在命令行中工作,而不是在代码中工作。我还尝试了以下方法:

  • 为用户NETWORK SERVICE 设置我的更新程序的完全权限
  • p.StartInfo.Verb = "runas" 开始进程
  • p.StartInfo.WorkingDirectory 更改为Environment.SystemDirectory
  • p.MachineName 更改为Environment.MachineName
  • 停止服务后让线程休眠5秒

但似乎没有任何影响。

任何想法如何得到我想要的?提前感谢您的帮助。

【问题讨论】:

  • 我见过服务需要一段时间(例如超过几毫秒)到stop 的情况,并且对start 的调用将失败。通常虽然错误消息明确说明了这一点。诸如“无法启动服务,它已经在运行”之类的东西。从命令行手动完成时,您的服务是否需要一段时间才能停止?
  • @JesseWebb,我已经尝试让线程手动休眠(将其添加到问题中)。在命令行中,通常需要大约 2 秒。

标签: c# windows service


【解决方案1】:

试试这个方法:

ServiceController sc = new ServiceController(svr_name);
if (sc.Status != ServiceControllerStatus.Stopped)
{
    sc.Stop();
    sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30));
}

放置一些异常处理以避免错误。

【讨论】:

  • 停止服务不是问题,而是启动它。但是,我用 start 方法尝试了你的建议,它导致了同样的错误Cannot start service FOVEA Service Debug on computer '.'
  • @Isalomon Cannot start service FOVEA Service Debug on computer '.'. at System.ServiceProcess.ServiceController.Start(String[] args) at System.ServiceProcess.ServiceController.Start() at ServerMaintenance.ServerMaintenance.DropboxCopy(Dictionary'2 theArgs) in C:\Users\mmueller\...\ServerMaintenance\ServerMaintenance.cs:line 120 at ServerMaintenance.Program.Main(String[] args) in C:\Users\mmueller\...\ServerMaintenance\Program.cs:line 54
  • 调查服务器上的事件(事件查看器)以发现任何问题。
  • @Isalomon 事件查看器输出服务已成功停止.. 与重启无关。我怀疑这是缺少权利的问题,但我不知道现在该怎么办:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-20
  • 2019-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多