开发者

Ensure a windows service is started from Visual Basic .Net

开发者 https://www.devze.com 2022-12-20 05:15 出处:网络
I have a WCF service being hosted in a Windows Service (using techniques discussed here) and it works great. I\'m now writing a (VB.Net) frontend app that needs to call that service, but I don\'t want

I have a WCF service being hosted in a Windows Service (using techniques discussed here) and it works great. I'm now writing a (VB.Net) frontend app that needs to call that service, but I don't want my users having to fiddle around with the services snap-in and starting the service manually.

Can I write some code to ensure the Windows Service is started, or start it if it isn't?

Edit: OF course, I can ensure the Service startup is set to automatic, but it doesn't need to be runn开发者_JAVA技巧ing all the time, and even then the frontend app still needs to be sure the service is running and start it if it isn't.


You can use the ServiceController class to manipulate a service as needed.

Example from MSDN using the Status property to check if a service needs to be started:

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


You can do something like

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

Remember to add reference to and import System.ServiceProcess

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号