如何在失败时重启Windows服务?

时间:2015-01-30 17:19:05

标签: c# windows-services

我遇到了这个question,看起来它会解决我想要做的事情,而且我试图在创建Process()对象时使用类似的代码" SC"从代码中调用命令。

    static void SetRecoveryOptions(string serviceName)
    {
        int exitCode;
        using (var process = new Process())
        {
            var startInfo = process.StartInfo;
            startInfo.FileName = "sc";
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;

            // tell Windows that the service should restart if it fails
            startInfo.Arguments = string.Format("failure \"{0}\" reset= 0 actions= restart/60000", serviceName);

            process.Start();
            process.WaitForExit();

            exitCode = process.ExitCode;
        }

        if (exitCode != 0)
            throw new InvalidOperationException();
    }

我尝试从几个位置调用该代码(例如服务安装程序的已提交事件处理程序,服务本身的OnStart等),但每次我在Process()时都会收到异常对象已创建。例外情况是:"由于对象的当前状态而不允许操作"。

我在这里缺少什么想法?

0 个答案:

没有答案
相关问题