我有一個WCF服務託管在Windows服務中(使用的技術討論爲here),並且它工作得很好。我現在正在編寫一個需要調用該服務的(VB.Net)前端應用程序,但我不希望我的用戶必須手動調整服務管理單元並啓動該服務。確保從Visual Basic啓動Windows服務.Net
我可以編寫一些代碼來確保Windows服務已啓動,或者如果啓動不了,則可以啓動它?
編輯︰當然,我可以確保服務啓動設置爲自動,但它不需要一直運行,即使如此,前端應用程序仍然需要確保該服務正在運行如果不是,則啓動它。
我有一個WCF服務託管在Windows服務中(使用的技術討論爲here),並且它工作得很好。我現在正在編寫一個需要調用該服務的(VB.Net)前端應用程序,但我不希望我的用戶必須手動調整服務管理單元並啓動該服務。確保從Visual Basic啓動Windows服務.Net
我可以編寫一些代碼來確保Windows服務已啓動,或者如果啓動不了,則可以啓動它?
編輯︰當然,我可以確保服務啓動設置爲自動,但它不需要一直運行,即使如此,前端應用程序仍然需要確保該服務正在運行如果不是,則啓動它。
您可以使用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)
你可以做這樣的事情
Dim controller As New ServiceController("ServiceNameHere")
If controller.Status = ServiceControllerStatus.Stopped Then
controller.Start()
End If
記住添加引用和進口System.ServiceProcess
完美的作品,謝謝。 – 2010-02-10 12:32:34