由于超时导致异常后,我可以继续使用 NetworkStream 吗?

Can I continue using a NetworkStream after an exception due to a timeout?

当从 NetworkStream 接收数据时,我可以配置 stream.ReadTimeout
当在配置的时间内没有收到数据时,我得到一个 SocketExceptionex.SocketErrorCode=SocketError.TimedOut

发生此异常后我可以继续使用该流吗,或者是否有可能以这种方式丢失一些字节?

示例代码:

using (TcpClient client = new TcpClient("127.0.0.1", 2000))
using (NetworkStream stream = client.GetStream())
using (StreamReader reader = new StreamReader(stream, Encoding.ASCII))
{
    stream.ReadTimeout = 5000;

    while (true)
    {
        int i;
        try
        {
            i = reader.Read();
        }
        catch (IOException ex)
        {
            SocketError socketError = SocketError.Success;
            if (ex.InnerException is SocketException)
                socketError = ((SocketException)ex.InnerException).SocketErrorCode;

            if (socketError == SocketError.TimedOut)
            {
                Console.WriteLine("no data received for 5 seconds");
                continue;
            }
            else throw;
        }
    }
}

我在 .NET 方面没有找到任何关于此的文档,但是 NetworkStream.ReadTimeout 使用(在 windows 上)setsockopt 本机函数,并且在这个函数的描述中它是清楚地说明了各种选项(在 SO_RCVTIMEOSO_SNDTIMEO 错误代码的描述中):

If a send or receive operation times out on a socket, the socket state is indeterminate, and should not be used; TCP sockets in this state have a potential for data loss, since the operation could be canceled at the same moment the operation was to be completed.