This question is based on the other question: How can a windows service programmatically restart itself?
I implemented one of the solutions in the previous question like so:
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()
I am seeing 2 problems with this:
- The event log throws this warning every time the service restarts itself:
Windows detected your registry file is still in use by other applications or services... 5 user registry handles leaked from ...
- The service might not restart itself sometimes. After looking into it, my best guess is that the service is ending before the process tries to restart it. The reason this is an issue is because the net stop command will fail since the service is already stopped, causing it to not execute the net start command.
Here's the full code:
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
Assuming I'm correct (big assumption) with issue 2, do you think replacing the Return statement with a Thread.Sleep(10000) command work?