Categories
NETCF

Waiting for a Process

There have been numerous occasions where I’ve needed to write code to launch another process and wait for it to complete, usually taking some action based on the exit code. Therefore I’ve got a handy helper method to do this. It has changed a few times and is made much simpler in .NETCF v2.0 by taking advantage of the Process class. Most recently I used the code in one of the book chapters to show automatic installation of the Microsoft Message Queue (MSMQ) components onto a Windows Mobile device. The method is named ShellWait, as the name implies it launches a process and waits, the return value is the exit code from the process. If the application doesn’t exist it returns -1 immediately.


[C#]


//helper function to launch a process and wait for the result code
private static int ShellWait(string app, string args)
{
   if (!File.Exists(app))
   {
      return -1;
   }



   Process p = Process.Start(app, args);
   p.WaitForExit();



   return p.ExitCode;
}


 


[VB]


Private Shared Function ShellWait(ByVal app As String, ByVal args As String) As Integer
   If Not File.Exists(app) Then
      Return -1
   End If

   Dim p As Process = Process.Start(app, args)
   p.WaitForExit()

   Return p.ExitCode
End Function

By Peter Foot

Microsoft Windows Development MVP