C# Stream.Read 超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17215966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Stream.Read with timeout
提问by Tobia
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
如何为 Read() 方法设置超时?谢谢
采纳答案by DonBoitnott
If this is System.IO.StreamReader, then set it on the BaseStream:
如果是System.IO.StreamReader,则将其设置在BaseStream:
streamReader.BaseStream.ReadTimeout = 2000; //milliseconds, so 2 seconds
回答by dsfgsho
You need to deal with the underlying stream. So, in case you are using a TcpClient, you can simply set the ReceiveTimeout:
您需要处理底层流。因此,如果您使用的是 TcpClient,您只需设置 ReceiveTimeout:
The ReceiveTimeoutproperty 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.
所述ReceiveTimeout属性确定的时间,该读取方法将阻塞,直到它能够接收数据量。该时间以毫秒为单位。如果在 Read 成功完成之前超时到期,则 TcpClient 将引发 IOException。默认情况下没有超时。
tcpClient.ReceiveTimeout = 5000;

