Ras*_*A M -1 c# windows-services
我正在编写一个Windows服务,检查特定服务并检查它.如果它停止它将启动它...
protected override void OnStart(string[] args)
{
Thread thread = new Thread(new ThreadStart(ServiceThreadFunction));
thread.Start();
}
public void ServiceThreadFunction()
{
try
{
ServiceController dc = new ServiceController("WebClient");
//ServiceController[] services = ServiceController.GetServices();
while (true)
{
if ((int)dc.Status == 1)
{
dc.Start();
WriteLog(dc.Status.ToString);
if ((int)dc.Status == 0)
{
//heartbeat
}
}
else
{
//service started
}
//Thread.Sleep(1000);
}
}
catch (Exception ex)
{
// log errors
}
}
Run Code Online (Sandbox Code Playgroud)
我希望服务检查另一项服务并开始... PLZ帮助我如何做到这一点
首先,为什么要将ServiceController的Status属性从方便的ServiceControllerStatus枚举转换为int?最好把它留作枚举.特别是因为您的Heartbeat代码(将其与0进行比较)将永远不会运行,因为ServiceControllerStatus没有0作为可能的值.
其次,你不应该使用while(true)循环.即使使用Thread.Sleep,你已经在那里评论过,这是一种不必要的资源消耗.您可以使用WaitForStatus方法等待服务启动:
ServiceController sc = new ServiceController("WebClient");
if (sc.Status == ServiceControllerStatus.Stopped)
{
sc.Start();
sc.WaitForStatus (ServiceControllerStatus.Running, TimeSpan.FromSeconds(30));
}
Run Code Online (Sandbox Code Playgroud)
这将等待最多30秒(或其他)服务达到运行状态.
更新:我重新阅读原始问题,我认为你在这里尝试做的事情甚至不应该用代码完成.如果我理解正确,您希望在安装时在WebClient服务上为您的服务设置依赖关系.然后,当用户在Service Manager中启动服务时,它将自动尝试启动相关服务.