Capture command line output (by character output, not having to wait per line)

后端 未结 1 612
遥遥无期
遥遥无期 2021-01-24 10:13

I\'m currently rendering the output of a command line process into a text box. The problem is that in a normal command prompt window, one of the lines that is written has a load

相关标签:
1条回答
  • 2021-01-24 10:34

    If you want asynchronous processing of the stdout of the given process on a per-character basis, you can use the TextReader.ReadAsync() method. Instead of the code you have to handle the OutputDataReceived event, just do something like this:

    process.Start();
    
    // Ignore Task object, but make the compiler happy
    var _ = ConsumeReader(process.StandardOutput);
    
    process.StandardInput.WriteLine( arguments.Command );
    process.StandardInput.WriteLine( "exit" );
    

    where:

    async Task ConsumeReader(TextReader reader)
    {
        char[] buffer = new char[1];
    
        while ((await read.ReadAsync(buffer, 0, 1)) > 0)
        {
            // process character...for example:
            Console.Write(buffer[0]);
        }
    }
    

    Alternatively, you could just create a dedicated thread and use that to call TextReader.Read() in a loop:

    process.Start();
    
    new Thread(() =>
    {
        int ch;
    
        while ((ch = process.StandardOutput.Read()) >= 0)
        {
            // process character...for example:
            Console.Write((char)ch);
        }
    }).Start();
    
    process.StandardInput.WriteLine( arguments.Command );
    process.StandardInput.WriteLine( "exit" );
    

    IMHO the latter is more efficient, as it doesn't require as much cross-thread synchronization. But the former is more similar to the event-driven approach you would have had with the OutputDataReceived event.

    0 讨论(0)
提交回复
热议问题