本人初次接触Window服务,写了一个关于数据库方面的后台服务..
现在程序能够成功运行,,
但是此服务是依赖于SQLSERVER,如果SQLSERVER在电脑启动完成时还没有成功启动,我的服务就不会运行了..
我希望SQLSERVER服务启动成功后在运行自己的服务..如果SQL服务停止我的服务也跟着停止.
自己想了三个方法.
1.设置 window Service 中的依赖项 (VS 中 有个ServiceDependeOn设置,,具体怎么设置就不明白了)
2.在自己后台启动时,检测SQL服务是否启动.如果没有启动,我的服务就一直等待.(怎么获取Windows Service 里的服务名.和服务运行的状态)
3.我的服务启动后利用循环不停的连接SQL,连接成功后,break 循环(这个方法感觉不是那么优雅)

解决方案 »

  1.   

    可以在ProjectInstaller中使用使用Service Dependencies
    using (ServiceProcessInstaller processInstaller = new ServiceProcessInstaller())
    {
        processInstaller.Account = ServiceAccount.LocalSystem;
        processInstaller.Username = null;
        processInstaller.Password = null;
     
        using (ServiceInstaller installer = new ServiceInstaller())
        {
            installer.DisplayName = "My wonderful windows service.";
            installer.StartType = ServiceStartMode.Automatic;
            installer.ServiceName = "MyService";
     
            installer.ServicesDependedOn = new string [] { "COMSysApp" };
     
            this.Installers.Add(processInstaller);
            this.Installers.Add(installer);
        }
    }代码来自:
    How to: Code Service Dependencies
    http://bloggingabout.net/blogs/jschreuder/archive/2006/12/07/How-to_3A00_-Code-Service-Dependencies.aspx
    另,关于ProjectInstaller:第三步: 将安装程序添加到服务应用程序
     
    Visual Studio.NET 随附有安装组件,可用来安装与服务应用程序相关联的资源。安装组件在正在安装到的系统上注册一项单个的服务,并使服务控制管理器知道该服务的存在。
    要正确安装服务,并不需要在安装程序中进行任何特殊编码。但是,如果需要向安装进程添加特殊功能,则可能偶尔需要修改安装程序的内容。
           将安装程序添加到服务应用程序的步骤是:
    1:在解决方案中,访问要向其中添加安装组件的服务的Design视图。
    2:在属性窗口中,单击添加安装程序链接
    这时项目中就添加了一个新类 ProjectInstaller 和两个安装组件 ServiceProcessInstaller 和 ServiceInstaller,并且服务的属性值被复制到组件。来自:
    http://dev.csdn.net/htmls/12/12056.html
      

  2.   

    这种功能不要搞什么检测,设置服务依赖关系...在ServicesDependedOn里填上服务名就行了,服务名可以在计算机管理工具的“服务”或注册表里查...Win7直接在任务管理器里就能查到...
      

  3.   


    ServicesDependedOn  里填上服务名,我已经填了,,没用啊
      

  4.   

    还是用第二种思路吧,可以用ServiceController这个类
            /// <summary>
            /// 获取一个服务的状态
            /// </summary>
            /// <param name="ServName"></param>
            /// <returns></returns>
            public static string GetServState(string servername)
            {
                try
                {
                    ServiceController sc = new ServiceController(servername);
                    return sc.Status.ToString();
                }
                catch
                { 
                    
                    return "";
                }
            }
    看一下这个代码自己再想一下就知道怎么解决了。