C# Stream.Read with timeout

徘徊边缘 提交于 2019-12-17 19:33:42

问题


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


回答1:


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

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



回答2:


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;


来源:https://stackoverflow.com/questions/17215966/c-sharp-stream-read-with-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!