0

I've got the following bit of C# code running on .NET Core 2.2 to launch a Java process and wait for its execution:

using (var validator = new Process())
{
validator.StartInfo.FileName = "java";
validator.StartInfo.Arguments = finalArguments;
validator.StartInfo.UseShellExecute = false;
validator.StartInfo.RedirectStandardOutput = true;
validator.StartInfo.RedirectStandardError = true;

try
{
    validator.Start();
    validator.WaitForExit();
}

When run on Linux, this code works absolutely fine - Java process runs and exits.

When run on Windows, the Java process will just hang for a long while for some reason and not properly exit:

Task manager view

If I pause the debugger, the debugger pauses on validator.WaitForExit();. If I kill the Java process manually, my application continues as normal.

What could be making the Java process hang and not exit correctly on Windows?

Edit: I'm running my function async so it doesn't hang the application, in case it makes a difference:

Task<OperationOutcome> validateWithJava = Task.Run(() => ValidateWithJava());
Vadim Peretokin
  • 2,221
  • 3
  • 29
  • 40
  • Try to do the same run in the console (cmd.exe): if run `java` `finalArguments` would it wait for user input, or exit immediately? – Renat Jun 07 '19 at 09:13
  • I've tried it in `cmd.exe` and yes, it did exit! – Vadim Peretokin Jun 07 '19 at 09:19
  • 1
    https://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why – Dmitry Bychenko Jun 07 '19 at 09:21
  • That sounds about right, there is a lot of output - but which solution from the many answers would you recommend? I'm pretty new to the C# world here. – Vadim Peretokin Jun 07 '19 at 09:25
  • Ah, I see it now: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.standardoutput?redirectedfrom=MSDN&view=netcore-2.2#System_Diagnostics_Process_StandardOutput "The example avoids a deadlock condition by calling p.StandardOutput.ReadToEnd before p.WaitForExit. A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardOutput.ReadToEnd and the child process writes enough text to fill the redirected stream" – Vadim Peretokin Jun 07 '19 at 09:30
  • That solved it! @DmitryBychenko could you submit this as an answer? My problem was exactly calling `.StandardOutput.ReadToEnd()` after `.WaitForExit()` – Vadim Peretokin Jun 07 '19 at 09:41
  • @Vadim Peretokin: I haven't *answered* your question: there's known issue with `ReadToEnd()` and `WaitForExit()`. That's why let me close the question as *duplicate* – Dmitry Bychenko Jun 07 '19 at 09:59
  • Yep, closing it sounds good! – Vadim Peretokin Jun 07 '19 at 11:03

0 Answers0