So I noticed that there's a method called WaitForExit that accepts and int as argument (milliseconds) so if the process isn't able to exit itself, I just killed it after some seconds.
Something like this.
if (!CMD.WaitForExit(3000))
CMD.Kill();
The thing is that meanwhile I'd like to save the output, so I noticed that there's an async method WaitForExitAsync but this one doesn't accept these milliseconds.
// Wait for exit async...
// Meanwhile save the output till it kills itself.
while (CMD.StandardOutput.ReadLine() != null)
standard_output = StandardOutput.ReadLine();
Any idea how to do this? Thanks!
CodePudding user response:
You need to use CancellationTokenSource. It has a ctor which accepts a TimeSpan
var timeoutSignal = new CancellationTokenSource(TimeSpan.FromSeconds(3));
try
{
await CMD.WaitForExitAsync(timeoutSignal.Token);
} catch (OperationCanceledException)
{
CMD.Kill();
}
When the CTS signals then the awaited operation will throw an OperationCanceledException. So you need to wrap your await call into a try-catch to handle cancelled operation properly.
