views:

290

answers:

2

Hello all,

I am totally a newbie to VB.net, now I am developping a Windows Service, which will start an *.exe when starting. How can I detect and re-start a process of this executable if it got killed by some other program?

My code is as below:

Public Class MyWinService
Dim RetVal
Protected Overrides Sub OnStart(ByVal args() As String)
    EventLog.WriteEntry("MyService Started")

    RetVal = Shell("JobService.exe", 1)

End Sub

Protected Overrides Sub OnStop()
    EventLog.WriteEntry("MyService Stopped")
    Dim myProcess = Process.GetProcessById(RetVal)
    myProcess.Kill()
End Sub

Protected Overrides Sub OnPause()
    EventLog.WriteEntry("MyService Paused")
End Sub

Protected Overrides Sub OnContinue()
    EventLog.WriteEntry("MyService Resumed")
End Sub

Protected Overrides Sub OnCustomCommand(ByVal command As Integer)
    If command = 200 Then
        EventLog.WriteEntry("Custom Command 200 invoked")
    ElseIf command = 210 Then
        EventLog.WriteEntry("Custom Command 210 invoked")
    End If
End Sub

Private Sub Process1_Exited(ByVal sender As System.Object, ByVal e As System.EventArgs)

End Sub

End Class

Thanks a lot in advance!

+3  A: 

The wrong way to do it is create a Process object in the OnStart() method. Tie a method to the Exited event of the process object that restarts the object. http://msdn.microsoft.com/en-us/library/system.diagnostics.process.onexited(VS.71).aspx has some information on the Exited event.

The correct way to do it is create a Timer object. Every X amount of minutes, create a Process object, check for the handle ID, and see if it's running. If not, then create a new executable, similar to what you did on the OnStart() method.

http://csharpstruggles.blogspot.com/2005/02/using-timer-in-windows-service.html

http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/bc175c60-f81b-4d1a-975d-717368468238

The elegant way is, as mentioned above, to do the work in the service itself.

bryanjonker
+2  A: 

You can use the process.start and the process.Exited methodes, like this:

Imports System.Diagnostics

Public Class Form1
Dim WithEvents proc As Process

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)_
  Handles Button1.Click
' start the process
proc = Process.Start(progName)
proc.EnableRaisingEvents = True
End Sub

Private Sub proc_Exited(ByVal sender As Object, ByVal e As System.EventArgs) _
  Handles proc.Exited
' restart the process whenever it exits
proc = Process.Start(progName)
proc.EnableRaisingEvents = True
End Sub

End Class
xpda