我想知道如何以我想要的方式重新启动我的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 循环时,我遇到了超时错误。我想这是因为服务已停止?
我在这里真正想要实现的是停止服务,然后在再次启动服务之前睡 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;
}
}
我有一个类似的 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;
}
我知道你可以这样做,但有时最好只是想简单。