【问题标题】:Ensure a windows service is started from Visual Basic .Net确保从 Visual Basic .Net 启动 Windows 服务
【发布时间】:2010-02-10 11:35:49
【问题描述】:

我有一个 WCF 服务托管在 Windows 服务中(使用讨论过的技术here),它运行良好。我现在正在编写一个需要调用该服务的 (VB.Net) 前端应用程序,但我不希望我的用户不得不摆弄服务管理单元并手动启动服务。

我可以编写一些代码来确保 Windows 服务已启动,或者如果没有启动它吗?

编辑:当然,我可以确保服务启动设置为自动,但它不需要一直运行,即使这样前端应用程序仍然需要确保服务正在运行,如果没有,则启动它。

【问题讨论】:

    标签: vb.net wcf windows-services


    【解决方案1】:

    您可以根据需要使用ServiceController 类来操作服务。

    MSDN 中使用 Status 属性检查是否需要启动服务的示例:

    ' Toggle the Telnet service - 
    ' If it is started (running, paused, etc), stop the service.
    ' If it is stopped, start the service.
    Dim sc As New ServiceController("Telnet")
    Console.WriteLine("The Telnet service status is currently set to {0}", sc.Status)
    
    If sc.Status.Equals(ServiceControllerStatus.Stopped) Or sc.Status.Equals(ServiceControllerStatus.StopPending) Then
       ' Start the service if the current status is stopped.
       Console.WriteLine("Starting the Telnet service...")
       sc.Start()
    Else
       ' Stop the service if its status is not set to "Stopped".
       Console.WriteLine("Stopping the Telnet service...")
       sc.Stop()
    End If
    
    ' Refresh and display the current service status.
    sc.Refresh()
    Console.WriteLine("The Telnet service status is now set to {0}.", sc.Status)
    

    【讨论】:

      【解决方案2】:

      你可以这样做

          Dim controller As New ServiceController("ServiceNameHere")
          If controller.Status = ServiceControllerStatus.Stopped Then
              controller.Start()
          End If
      

      记得添加对 System.ServiceProcess 的引用并导入

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-28
        • 2014-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多