2010-02-10 47 views
1

我有一个WCF服务托管在Windows服务中(使用的技术讨论为here),并且它工作得很好。我现在正在编写一个需要调用该服务的(VB.Net)前端应用程序,但我不希望我的用户必须手动调整服务管理单元并启动该服务。确保从Visual Basic启动Windows服务.Net

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

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

回答

2

您可以使用ServiceController类来根据需要操作服务。使用Status属性从MSDN

实例来检查服务需要启动:

' 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) 
+0

完美的作品,谢谢。 – 2010-02-10 12:32:34

2

你可以做这样的事情

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

记住添加引用和进口System.ServiceProcess