gpt4 book ai didi

c# - NetworkStream:ReadTimeout 及其效果 Read()

转载 作者:可可西里 更新时间:2023-11-01 02:42:06 30 4
gpt4 key购买 nike

我对如何使用 ReadTimeout 以及它如何影响 Read() 感到困惑。

当尝试读取网络流时,有 3 种情况,假设我们正在尝试读取 X 个字节:

  1. 数据可用,字节< X
  2. 数据可用,bytes = X
  3. 数据可用,字节数 > X
  4. 没有可用数据,ReadTimeout > 0
  5. 没有可用数据,ReadTimeout = 0

文档有点模棱两可,没有明确提及 Read() 调用中的 ReadTimeout,或者 ReadTimeout 是否影响 Read() 调用。

This method reads data into the buffer parameter and returns the number of bytes successfully read. If no data is available for reading, the Read method returns 0. The Read operation reads as much data as is available, up to the number of bytes specified by the size parameter.

我的理解是针对以上5种情况:

  1. Read() 将读取 X 字节并立即返回。 ReadTimeout 无所谓
  2. Read() 将读取 X 字节并返回
  3. Read() 将读取 X 字节并返回。需要再次调用read读取剩余的X字节。
  4. 调用 Read() 将等待 ReadTimeout 一段时间以获取数据。
  5. Read() 将立即返回 0。

如果有人能提供一些说明,将不胜感激。

谢谢。

最佳答案

如果您查看 source for NetworkStream ,您会看到您的场景 1 - 4 并且理解是正确的(NetworkStream 只是在套接字上调用 read() )。过期超时的结果是 IOException,内部 SocketException 指示超时。

场景 5 不适用:零的 ReadTimeout 不存在,它要么是负 1(-1,表示无限)要么 >= 1。所以场景。 5 要么永远阻塞,要么得到一个带有内部 SocketException 的 IOException 指示一些错误。

关于c# - NetworkStream:ReadTimeout 及其效果 Read(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46726062/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com