Skip to main content
 首页 » 编程设计

c#之C#如何自行重启Windows服务

2024年02月06日16bjzhanghao

<分区>

我创建了一个服务,我通过 MSMQ 向该服务发送命令。

现在我需要重新启动服务,但是当它到达停止命令时它只是抛出错误或者它无法读取下一行,因为执行此任务的服务停止了。

我使用的代码是:

ServiceController service = new ServiceController(serviceName); 
            try 
            { 
                int millisec1 = Environment.TickCount; 
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); 
                ShutdownService(serviceName, timeoutMilliseconds); 
 
                // count the rest of the timeout 
                int millisec2 = Environment.TickCount; 
                timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1)); 
 
                service.Start(); 
                service.WaitForStatus(ServiceControllerStatus.Running, timeout); 
            } 
            catch (Exception ex) 
            { 
                s_log.Error(ex); 
            } 

当服务停止时,我如何按逻辑自行重启服务,它不会执行下一行代码。