JohnWick
JohnWick

Reputation: 5149

StandardOutput.ReadToEndAsync Hangs

var process = new Process();
var startInfo = new ProcessStartInfo();
startInfo.FileName = @"cmd.exe";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
process.StartInfo = startInfo;
process.Start();
await process.StandardInput.WriteLineAsync("curl http://example.com");
var response = await process.StandardOutput.ReadToEndAsync();

Anyone know why this hangs on the last line? Have researched this a bit and have seen deadlocks mentioned. Other solutions I have found are super ugly and seem to have been written before the Async methods were added to .NET (they use the Begin/End paradigm).

Upvotes: 0

Views: 531

Answers (1)

user2250152
user2250152

Reputation: 20823

You need to call exit command to exit the process. Then StandardOutput.ReadToEndAsync will return the response.

var process = new Process();
var startInfo = new ProcessStartInfo();
startInfo.FileName = @"cmd.exe";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
process.StartInfo = startInfo;
process.Start();
await process.StandardInput.WriteLineAsync("curl http://example.com");
await process.StandardInput.WriteLineAsync("exit");
var response = await process.StandardOutput.ReadToEndAsync();

Upvotes: 2

Related Questions