我想知道如何以我希望的方式重新启动Windows服务。
我有这个解决方案:
private const int RestartTimeout = 60000; // 1 minute
public void Control(string serviceName)
{
service = new ServiceController(serviceName);
}
public bool RestartService()
{
try
{
Control("MyService");
service.Refresh();
if (service.Status != ServiceControllerStatus.Stopped)
{
mytimer.Enabled = false;
service.Stop();
int i = 0;
service.Refresh();
while (service.Status == ServiceControllerStatus.Stopped || service.Status == ServiceControllerStatus.StopPending)
{
i++;
Thread.Sleep(100);
if (i >= RestartTimeout / 100)
{
return false;
}
}
service.Start();
return true;
}
service.Start();
return true;
}
catch (Exception ex)
{
return false;
}
}
到达while循环时出现超时错误。我想这是因为服务已经停止了?
我真正想要达到的目的是停止服务然后再睡一分钟再开始服务。
请帮忙。谢谢!
答案 0 :(得分:1)
我这样解决了(当然你需要以管理员权限启动你的应用程序!):
小建议:将您的问题分成多个部分(多种方法),因为如果出现错误,您可以将其缩小到少量行。
public void RestartService(string serviceName)
{
if (StopService(serviceName) == true)
{
Thread.Sleep(60000);
if (StartService(serviceName) == true)
{
MessageBox.Show("Service started succesfully");
}
}
}
private bool StartService(string serviceName)
{
ServiceController service = new ServiceController(serviceName);
try
{
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running);
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
private bool StopService(string serviceName)
{
ServiceController service = new ServiceController(serviceName);
try
{
if (service.Status != ServiceControllerStatus.Stopped)
{
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped);
return true;
}
else if (service.Status == ServiceControllerStatus.Stopped)
{
return true;
}
return false;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
答案 1 :(得分:0)
我有一个类似的asp.net项目,我使用这个代码,这是有效的。
try
{
ServiceController service = new ServiceController(service_name, computer_name);
if (service.Status != ServiceControllerStatus.Running)
{
return false;
}
else
{
service.Stop();
Thread.Sleep(60000);
service.Start();
}
}
catch (Exception exc)
{
return false;
}
我知道你可以做到这一点,但有时它更好只是简单地思考。