views:

130

answers:

1

I have a command line executable that is run from a C# class library. In some very rare situations the executable will hang because of the command line data passed to it. Unfortunetely this causes the application calling the c# DLL to hang whilst it waits indefinitely for the process to exit.

If the command line exe doesnt finish execution within 1 second its never going to exit. What I'd like to do is spawn a timer just after the process has started and force close the process if it hasnt exited within a few seconds.

What is the best approach here? The solution needs to have minimal impact upon performance because this command line process is the bottleneck in a highly repetitive task.

Edit: Any reason why I should use System.Timer rather than Threading.Timer or vice versa?

            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.CreateNoWindow = false;
            startInfo.UseShellExecute = true;
            startInfo.WorkingDirectory = workingDirectory;
            startInfo.FileName = commandLineExe;
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            startInfo.Arguments = strArguments;



            // Call WaitForExit and then the using statement will close.
            using (Process exeProcess = Process.Start(startInfo))
            {

                exeProcess.WaitForExit();
            }

Please refrain from suggestions that I should try and figure out why the command line app is hanging, or that I should refactor the command line functionality into the source code. We are actively working on that problem but stability of the application needs to come first.

+1  A: 

Just add:

// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo)) {
    if(!exeProcess.WaitForExit(1000))
          exeProcess.Kill();
}
Reed Copsey
Oh how embarrassing. I cant believe I didnt see that before.
Alex