C# 等待其他服务启动

3
我正在编写一个依赖于其他服务的Windows服务,我应该如何等待其他服务启动?
谢谢
6个回答

4

我认为你应该这样写:

installer.ServicesDependedOn = new string[] { "依赖服务" };

就像这样:

using (ServiceProcessInstaller processInstaller = new ServiceProcessInstaller())
{
    processInstaller.Account = ServiceAccount.LocalSystem;
    processInstaller.Username = null;
    processInstaller.Password = null; 

    using (ServiceInstaller installer = new ServiceInstaller())
    {
        installer.DisplayName = "yourservice.";
        installer.StartType = ServiceStartMode.Automatic;
        installer.ServiceName = "YourService";

        installer.ServicesDependedOn = new string [] { "DependenceService" };
        this.Installers.Add(processInstaller);
        this.Installers.Add(installer);
    }
}

祝你好运


依赖服务在您的服务启动时会自动启动,但当它们已经运行时,您的服务不会自动启动。这就是我理解的问题所在。 - undefined
抱歉...如果我误解了问题,我很抱歉。 - undefined
我知道这是一个干净的解决方案,但作为一种变通方法,我们可以每隔N秒检查所需服务的状态:ServiceController Name = new ServiceController(); byServiceName.ServiceName = "ServiceWanted";然后: if (name.Status == ServiceControllerStatus.Running) { //执行服务的操作 } - undefined
1
你为什么要通过编程来实现这个,而不是通过设计师呢? - undefined

3
除了其他答案已经指出的内容之外,如果其中一个服务是SQL Server,则需要确保特定数据库以及SQL Server服务本身可用。我使用类似以下函数的功能:
public class DbStatus
{
    public static bool DbOnline()
    {
        const int MaxRetries = 10;
        int count = 0;

        while (count < MaxRetries)
        {
            try
            {
                // Just access the database. any cheap query is ok since we don't care about the result.
                return true;
            }
            catch (Exception ex)
            {
                Thread.Sleep(30000);
                count++;
            }
        }
        return false;
    }
}

1

您需要指定依赖项。您可以在您的Installer类中完成此操作。

进一步澄清

您应该将 Installer 类作为自定义操作使用到您的设置项目中,以安装您的服务。如果没有,请发表评论,我会更新这个答案并告诉您如何操作。

在您的 Installer 类设计器中,您应该会看到两个组件:serviceInstaller 和 serviceProcessInstaller。我不记得其中哪一个了,但其中一个有一个属性,允许您指定一个多行字符串,列出您的服务所依赖的服务名称。


你能解释一下你的意思吗?这会对我有什么帮助?谢谢。 - James May
使用ServiceInstaller类(http://msdn.microsoft.com/en-us/library/system.serviceprocess.serviceinstaller.aspx)安装服务时,可以通过ServicesDependedOn属性添加依赖项。 - undefined

1
正如其他人所说,您应该使用ServiceInstaller类,但您不需要完整的安装程序项目。 您可以使用InstallUtil.exe进行快速安装,这是一个随.NET Framework一起提供的命令行实用程序。

0

你对其他服务有控制权吗? 如果是的话,请让它们启动你,如果不是的话,我猜你还是得自己启动并监控正在发生的事情。 可以通过注册到WMI来在其他进程启动时收到通知 - 这方面有一个问题。


有一种方法可以指定Windows的服务依赖关系,这样它就不会尝试在其他服务完成启动之前启动您的服务。 - undefined
这是正确的,但如果你希望在其他服务已经运行时才启动你的服务,这并没有帮助-而且我认为这就是问题所在。 - undefined
@开发者:它在哪方面不起作用?将依赖项和启动类型设置为自动。 - undefined

0
在您的服务项目中,添加一个项目安装程序如此处所述。您的ProjectInstaller的属性之一将是ServicesDependedOn。当您将服务添加到该字符串数组中(您可以通过IDE完成此操作),它们将需要在您的服务启动之前启动。如果它们未启动,SCM将尝试启动它们。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接