vb.net - 如果没有可读内容,StreamReader 将挂起

vb.net - StreamReader hangs if there is nothing to read

我有这个代码来读取 TCP 流:

  Function checkdata() As String
    Dim Stream As NetworkStream = client.GetStream()
    sr = New StreamReader(Stream)

    Dim s As String = sr.ReadLine() <------------
    Return s
  End Function

问题是如果流中没有新数据,代码会挂在标记的行上。为什么?我该如何解决这个问题?

你能用 NetworkStream.DataAvailable 属性 吗?

Function checkdata() As String
    Dim Stream As NetworkStream = client.GetStream()
    If Stream.DataAvailable Then
        Dim SR = New StreamReader(Stream)
        Dim s As String = SR.ReadLine()
        Return s
    Else
        Return Nothing
    End If
End Function