19

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

Tobia
  • 9,165
  • 28
  • 114
  • 219

2 Answers2

29

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

streamReader.BaseStream.ReadTimeout = 2000;  //milliseconds, so 2 seconds
DonBoitnott
  • 10,787
  • 6
  • 49
  • 68
  • do you have any idea what is default timeout value ? – SHAHS Oct 27 '17 at 12:50
  • @SHAHS No. It's not obvious to me looking at the source where that value comes from. Best I can suggest is put a breakpoint on it and look. – DonBoitnott Oct 27 '17 at 12:59
  • When applied to a /dev/ttysomething on linux, it raises an exception: System.InvalidOperationException: Timeouts are not supported on this stream. – Giorgio Barchiesi Feb 01 '23 at 15:49
13

You need to deal with the underlying stream. So, in case you are using a TcpClient, you can simply set the ReceiveTimeout:

The ReceiveTimeout property determines the amount of time that the Read method will block until it is able to receive data. This time is measured in milliseconds. If the time-out expires before Read successfully completes, TcpClient throws a IOException. There is no time-out by default.

 tcpClient.ReceiveTimeout = 5000;
dsfgsho
  • 2,731
  • 2
  • 22
  • 39