call StreamReader.EndOfStream Blocking thread?

zzf 1 Reputation point
2022-04-16T15:31:30.56+00:00
static void Main(string[] args)
        {
            EventWaitHandle _mainProcessEventWait = new EventWaitHandle(false, EventResetMode.ManualReset);
            bool _run = true;
            var psi = new ProcessStartInfo()
            {
                FileName = "cmd.exe",
                CreateNoWindow = true,
                WorkingDirectory = AppContext.BaseDirectory,
                UseShellExecute = false,
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
            };
            Process process = Process.Start(psi);

            var sinput = Task.Factory.StartNew(() =>
            {
                using (StreamWriter sw = process.StandardInput)
                {
                    while (_run)
                    {
                        var _command = Console.ReadLine();
                        sw.WriteLine(_command);
                        if (_command == "exit" || _command == "exit;")
                        {
                            _run = false;
                            _mainProcessEventWait.Set();
                        }
                    }
                }
            });
            var sout = Task.Factory.StartNew(() =>
            {
                using (StreamReader sr = process.StandardOutput)
                {
                    char[] buffer = new char[1];
                    while (sr.BaseStream.CanRead)
                    {
                        if(!sr.EndOfStream) //when reading to end. this code will clog current thread? 
                        sr.Read(buffer, 0, 1);//clog current thread 
                        sr.ReadLine();//clog current thread 
                        Console.Write(buffer);
                    }
                }
            });
            _mainProcessEventWait.WaitOne();
            Console.WriteLine("end");
        }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
8,245 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 95,156 Reputation points
    2022-04-17T08:10:41.35+00:00

    If you want to intercept and display the output, then try this:

    var sout = Task.Factory.StartNew( ( ) =>
    {
        process.StandardOutput.BaseStream.CopyTo( Console.OpenStandardOutput( ) );
    } );
    var serr = Task.Factory.StartNew( ( ) =>
    {
        process.StandardError.BaseStream.CopyTo( Console.OpenStandardOutput( ) );
    } );
    

    Note that CanRead indicates that the stream supports reading; it does not mean that the data are available.