C# Stream.Read with timeout

Tobia picture Tobia · Jun 20, 2013 · Viewed 28.2k times · Source

I have this streamreader:

            Boolean read = false;
            while (wline!="exit")
            {

                while (!read || streamReader.Peek() >= 0)
                {
                    read = true;
                    Console.Write((char)streamReader.Read());
                }
                wline = Console.ReadLine();
                streamWriter.Write(wline+"\r\n");
                streamWriter.Flush();

            }

How to set a timeout for Read() method? thanks

Answer

DonBoitnott picture DonBoitnott · Jun 20, 2013

If this is System.IO.StreamReader, then set it on the BaseStream:

streamReader.BaseStream.ReadTimeout = 2000;  //milliseconds, so 2 seconds