Search code examples
c#.netprocess

Process.WaitForExit() triggers too fast


Here is the code I use to run extern executable (unmanaged) from c# code:

static void Solve()
{
    Process newProc = new Process();
    newProc.StartInfo.WorkingDirectory =
        Path.Combine(Directory.GetCurrentDirectory(), "Data");
    newProc.StartInfo.FileName = "solver.exe";
    newProc.StartInfo.CreateNoWindow = true;
    newProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    try
    {
        newProc.Start();
        newProc.WaitForExit();
    }
    catch (Exception e)
    {
        StreamWriter errorReporter = new StreamWriter("ErrorLog.txt", true);
        errorReporter.WriteLine(message);
        errorReporter.Close();
    }
    
    newProc.Close();
}

In my case solver works about 30 seconds if I start it manually. The result of solver.exe actions is a file. But when I call for it from code, it exits almost the same moment and does nothing. No output comes from it, output file is not generated.

Also, process is started correctly, no errors are thrown. Is there any problems in the code above or should I just start with checking solver.exe?


Solution

  • Your process is probably failing in an unforeseen way. You can only know to read the Output and Error stream and store it in a file (or write it to the console, or eventlog)

    Remember that if you need to read the Error AND the Output streams simultanuously to do it async/eventdriven. Otherwise the streams will block and not produce any output or not the output you're after.

    StreamWriter errorReporter = new StreamWriter("SOLVER-OUTPUT-ERROR.txt", true);
    
    newproc.StartInfo.RedirectStandardOutput = true;
    newproc.StartInfo.RedirectStandardError = true;
    
    newproc.OutputDataReceived += (sender, args) => errorReporter.WriteLine(args.Data);
    newproc.ErrorDataReceived += (sender, args) => errorReporter.WriteLine(args.Data);
    newproc.StartInfo.UseShellExecute=false;
    
    newProc.Start();
    newProc.BeginOutputReadLine();
    newProc.BeginErrorReadLine();
    
    newProc.WaitForExit();
    
    errorReporter.Close();