Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Stream.Read with timeout

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

like image 889
Tobia Avatar asked Jun 20 '13 14:06

Tobia


2 Answers

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

streamReader.BaseStream.ReadTimeout = 2000;  //milliseconds, so 2 seconds
like image 155
DonBoitnott Avatar answered Sep 21 '22 08:09

DonBoitnott


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;
like image 36
dsfgsho Avatar answered Sep 18 '22 08:09

dsfgsho