none
Wait until the process has exited using Process.HasExited or Process.WaitForExit? RRS feed

  • Question

  • I want to wait for a process exited, use Process.HasExited or Process.WaitForExit? what different for two functions?

          Dim p As New Process
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
            p.StartInfo.FileName = "test.exe"

                p.Start()
               
                Do Until p.HasExited = True Or use p.WaitForExit()
                    Threading.Thread.Sleep(100)
                Loop

                If p.ExitCode = 0 Then
                    Return True
                Else
                    Return False
                End If

    Friday, February 14, 2020 12:29 PM

Answers

  • Well, if you use Process.WaitForExit() your process will wait until test.exe has terminated.  Although this would be the most efficient approach, it is inappropriate for use in a process that displays a user interface.

    Looping on Process.HasExited would be less efficient because the system would waste resources as your thread bounces back and forth between being scheduled for execution, executing and then relinquishing control when sleeping.  And this loop would also be inappropriate when a user interface is present.

    • Marked as answer by gaxjyxq Friday, February 14, 2020 10:25 PM
    Friday, February 14, 2020 1:50 PM

All replies

  • Best to read the documentation

    Process.WaitForExit, Process.HasExited. Process.WaitForExit is an overloaded method. Check out the See also too for WatForExit and ExitCode.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Friday, February 14, 2020 1:34 PM
    Moderator
  • Well, if you use Process.WaitForExit() your process will wait until test.exe has terminated.  Although this would be the most efficient approach, it is inappropriate for use in a process that displays a user interface.

    Looping on Process.HasExited would be less efficient because the system would waste resources as your thread bounces back and forth between being scheduled for execution, executing and then relinquishing control when sleeping.  And this loop would also be inappropriate when a user interface is present.

    • Marked as answer by gaxjyxq Friday, February 14, 2020 10:25 PM
    Friday, February 14, 2020 1:50 PM