troubleshooting Question

problem running a process - exit event being called twice

Avatar of andieje
andieje asked on
Visual Basic.NET
7 Comments1 Solution1934 ViewsLast Modified:

I have some code for running a process in 2005. The problem is that the process exit event is being called twice even though after it is called the first time i am setting myProcess.EnableRaisingEvents = False

On my screen i see the output "process exited" twice. The second time an eception is thrown in the exit event saying there is no process associated with the object.

any ideas??? :)

thanks a lot


Module Module1

    ' This line of code must be at Class / Module level to enable the
    ' Exited event.
    Dim WithEvents p As Process = New Process()

    Dim exitCode As Integer = -1

    Sub Main()

        Dim si As New ProcessStartInfo

        si.FileName = "C:\xmltv\xmltv-0.5.44-win32\xmltv-0.5.44-win32\xmltv.exe"
        si.Arguments = "tv_grab_uk_rt --output FILE"
        si.RedirectStandardError = True
        si.RedirectStandardOutput = True
        si.UseShellExecute = False
        si.CreateNoWindow = True
        p.StartInfo = si

        While exitCode <> 0

            p.EnableRaisingEvents = True

            ' This needs to be in the code other wise you will not see any output
            ' Start the asynchronous read of the process output streams

            ' Wait until the process is done.
        End While


    End Sub

    Friend Sub ProcessExited(ByVal sender As Object, _
       ByVal e As System.EventArgs) Handles p.Exited

        Dim myProcess As Process = DirectCast(sender, Process)
        Console.WriteLine("The process exited, raising " & _
                "the Exited event at: " & myProcess.ExitTime & _
                "." & System.Environment.NewLine & _
                "Exit Code: " & myProcess.ExitCode & System.Environment.NewLine)

        exitCode = myProcess.ExitCode

        ' Need to set this to False otherwise this function will be called twice
        myProcess.EnableRaisingEvents = False
        Console.WriteLine("process closed")
    End Sub

    'error output and standard output code removed for clarity
End Module
Join our community to see this answer!
Unlock 1 Answer and 7 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 7 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros