开发者

How to re-run an executable in VB.net

开发者 https://www.devze.com 2022-12-19 12:23 出处:网络
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 ot

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开发者_Go百科 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!


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.


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
0

精彩评论

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