How to asynchronously read the standard output stream and standard error stream at once

后端 未结 4 2015
终归单人心
终归单人心 2020-11-29 04:33

I want to read the ouput of a process in the form as is in a console (standard output is blended with standard error in one stream). Is there a way how to do it?

I w

4条回答
  •  无人及你
    2020-11-29 05:32

    Do you mean something like this?

    SynchronizationContext _syncContext;
    MyForm()
    {
        _syncContext = SynchronizationContext.Current;
    }
    
    void StartProcess()
    {
        using (var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "myProcess.exe",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                }
            })
        {
            process.OutputDataReceived += (sender, args) => Display(args.Data);
            process.ErrorDataReceived += (sender, args) => Display(args.Data);
    
            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
    
            process.WaitForExit(); //you need this in order to flush the output buffer
        }   
    }
    
    void Display(string output)
    {
        _syncContext.Post(_ => myTextBox.AppendText(output), null);
    }
    

提交回复
热议问题