【发布时间】:2012-02-10 19:38:17
【问题描述】:
这个问题是基于另一个问题: How can a windows service programmatically restart itself?
我在上一个问题中实现了一个解决方案,如下所示:
Dim proc As New Process()
Dim psi As New ProcessStartInfo()
psi.CreateNoWindow = True
psi.FileName = "cmd.exe"
psi.Arguments = "/C net stop YOURSERVICENAMEHERE && net start YOURSERVICENAMEHERE"
psi.LoadUserProfile = False
psi.UseShellExecute = False
psi.WindowStyle = ProcessWindowStyle.Hidden
proc.StartInfo = psi
proc.Start()
我发现这有 2 个问题:
- 每次服务重新启动时,事件日志都会引发此警告:
Windows detected your registry file is still in use by other applications or services... 5 user registry handles leaked from ... - 服务有时可能不会自行重新启动。经过调查,我最好的猜测是该服务在进程尝试重新启动它之前就结束了。这是一个问题的原因是 net stop 命令将失败,因为服务已经停止,导致它无法执行 net start 命令。
这是完整的代码:
Private Sub Timer_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles _timer.Elapsed
' we do not want the timer stepping on itself (ie. the time interval elapses before the first call is done processing
_timer.Stop()
' do some processing here
Dim shouldRestart As Boolean = ProcessStuff()
If shouldRestart Then
Dim proc As New Process()
Dim psi As New ProcessStartInfo()
psi.CreateNoWindow = True
psi.FileName = "cmd.exe"
psi.Arguments = "/C net stop ""My Cool Service"" && net start ""My Cool Service"""
psi.LoadUserProfile = False
psi.UseShellExecute = False
psi.WindowStyle = ProcessWindowStyle.Hidden
proc.StartInfo = psi
proc.Start()
Return
End If
_timer.Start()
End Sub
假设我对问题 2 是正确的(大假设),您认为用 Thread.Sleep(10000) 命令替换 Return 语句是否有效?
【问题讨论】:
标签: .net windows windows-services