How to read to end process output asynchronously in C#?

后端 未结 4 489
醉梦人生
醉梦人生 2020-12-01 19:56

I have problem with reading the output of one Process asynchronously in C#. I found some other similar questions on this site but they don\'t really help me. Here is what I

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 20:24

    There are few things that are getting in the way of it...

    The console app is probably using "\b" backspace to overwrite the percentage, its maybe not flushing to the stdout stream after every write, and the BeginOutputReadLine presumably waits for the end of line before giving you data.

    See how you get on with reading process.StandardOutput.BaseStream via BeginRead (this code isn't proper async and the "\b"s will need processed differently if your putting progress in a form):

            while (true)
            {
                byte[] buffer = new byte[256];
                var ar = myProcess.StandardOutput.BaseStream.BeginRead(buffer, 0, 256, null, null);
                ar.AsyncWaitHandle.WaitOne();
                var bytesRead = myProcess.StandardOutput.BaseStream.EndRead(ar);
                if (bytesRead > 0)
                {
                    Console.Write(Encoding.ASCII.GetString(buffer, 0, bytesRead));
                }
                else
                {
                    myProcess.WaitForExit();
                    break;
                }
            }
    

提交回复
热议问题