c# - 当 NetworkStream.Read(byte[], int, int) 需要返回 -1 时,它会中止 () 运行它的线程吗?

标签 c# networking stream

        NetworkStream stream = socket.GetStream();

        if (stream.CanRead)
        {
            while (true)
            {
                int i = stream.Read(buf, 0, 1024);
                result += Encoding.ASCII.GetString(buf, 0, i);
            }
        }

以上代码旨在在单独的线程上运行时从 TcpClient 检索消息。 Read 方法工作正常,直到它应该返回 -1 以指示不再有任何内容可读;相反,它只是在没有任何明显原因的情况下终止它正在运行的线程——使用调试器跟踪每个步骤表明它只是在该行之后立即停止运行。

我也尝试用 try ... catch 封装它,但没有成功。

这可能是什么原因造成的?

编辑:我试过了

        NetworkStream stream = socket.GetStream();

    if (stream.CanRead)
    {
        while (true)
        {
            int i = stream.Read(buf, 0, 1024);
            if (i == 0)
            {
                break;
            }
            result += Encoding.ASCII.GetString(buf, 0, i);
        }
    }

感谢@JonSkeet,但问题仍然存在。线程在该 read 行终止。

EDIT2:我像这样修复了代码并且它起作用了。

    while (stream.DataAvailable)
    {
        int i = stream.Read(buf, 0, 1024);
        result += Encoding.ASCII.GetString(buf, 0, i);
    }

我觉得问题很简单,就是我想的不够透彻。谢谢大家看这个!

最佳答案

不,Stream.Read当没有可读取的内容时返回 0,而不是 -1:

Return value
The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.

我的猜测是,实际上,没有抛出异常并且线程没有被中止 - 但它只是永远循环。如果您在调试器中逐步执行,您应该能够看到这一点。无论发生什么,你的“快乐”终止条件永远不会被击中......

关于c# - 当 NetworkStream.Read(byte[], int, int) 需要返回 -1 时,它会中止 () 运行它的线程吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10528311/

相关文章:

c# - 如何播放音频流并同时加载到其中?

c# - SPWorkflowActivationProperties 对象引用

windows - 多宿主系统上的 UDP 广播

python - 网络 - 测试连接性 [Python 或 C]

c++ - streamsize、streamoff 和其他与流相关的数据类型的实际类型是什么

android - 在 Android Listview 中显示流数据的最佳方式

c# - 为什么 Powershell 无法识别 Add_Type block 中的 System.Data?

c# - Windows Azure - 在 Windows Azure IIS 存储中提供未知 (mp4) MIME 类型

c# - 与宽高比匹配的最小尺寸

python - 通过 localhost 访问时无法通过 ip 地址访问 django 应用程序