Asynchronously read cmd output in .NET - Hanging on process input request

北慕城南 提交于 2019-12-12 02:44:42

问题


I'm asynchronously reading the output from a batch file, after starting it with some parameters. If the batch file is waiting for input - the input request text is not being redirected - unless the process is terminated (which is obviously too late to respond).

If executed in a standard cmd window, the prompt is:

OpenEdge Release 10.2B07 as of Fri Sep  7 02:16:54 EDT 2012
testdb already exists.
Do you want to over write it? [y/n]:

The output when using redirect will hang, without triggering the outputdatarecieved event, so I cannot process the input request and respond accordingly. The console does not read the last line (input request):

OpenEdge Release 10.2B07 as of Fri Sep  7 02:16:54 EDT 2012
testdb already exists.

Code:

Private Sub someMethod()
    Dim process As New Process()
    process.StartInfo = New ProcessStartInfo("C:\OEV10\bin\_dbutil")
    process.StartInfo.WorkingDirectory = "C:\Temp\"
    process.StartInfo.Arguments = "prorest testdb C:\Temp\testdb.bck -verbose"
    process.EnableRaisingEvents = True

    With process.StartInfo
        .UseShellExecute = False
        .RedirectStandardError = True
        .RedirectStandardOutput = True
        .RedirectStandardInput = True
        .CreateNoWindow = False
        .StandardOutputEncoding = System.Text.Encoding.GetEncoding(Globalization.CultureInfo.CurrentUICulture.TextInfo.OEMCodePage)
        .StandardErrorEncoding = System.Text.Encoding.GetEncoding(Globalization.CultureInfo.CurrentUICulture.TextInfo.OEMCodePage)
    End With

    AddHandler process.Exited, AddressOf ProcessExited
    AddHandler process.OutputDataReceived, AddressOf Async_Data_Received2
    AddHandler process.ErrorDataReceived, AddressOf Async_Data_Received2

    process.Start()
    process.BeginOutputReadLine()
    process.BeginErrorReadLine()
End Sub

Private Sub Async_Data_Received2(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
    Console.WriteLine(e.Data)
End Sub

回答1:


You can write your own text stream reader routine, which will read and report incomplete line. Here is a simple C# implementation:

public static async Task ReadTextReaderAsync(TextReader reader, IProgress<string> progress) {
    char[] buffer = new char[1024];
    for(;;) {
        int count = await reader.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
        if(count==0) {
            break;
        }
        progress.Report(new string(buffer, 0, count));
    }
}

This implementation just read strings from TextReader and report them back thru IProgress<string> instance. It does not split strings by new line characters, but preserve them inside strings. And a test program:

public static void Main() {
    ProcessStartInfo psi = new ProcessStartInfo("Test.cmd") {
        UseShellExecute=false,
        RedirectStandardOutput=true,
        RedirectStandardError=true
    };
    Process p = Process.Start(psi);

    // Progress<T> implementation of IProgress<T> capture current SynchronizationContext,
    // so if you create Progress<T> instance in UI thread, then passed delegate
    // will be invoked in UI thread and you will be able to interact with UI elements.
    Progress<string> writeToConsole = new Progress<string>(Console.Write);

    Task stdout = ReadTextReaderAsync(p.StandardOutput, writeToConsole);
    Task stderr = ReadTextReaderAsync(p.StandardError, writeToConsole);

    // You possibly want asynchronous wait here, but for simplicity I will use synchronous wait.
    p.WaitForExit();
    stdout.Wait();
    stderr.Wait();
}


来源:https://stackoverflow.com/questions/33849991/asynchronously-read-cmd-output-in-net-hanging-on-process-input-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!