我有一个程序,其中有几个并行进程写入日志文件,主程序也在读取日志并将其汇集到文本字段中。
问题是,到了一定程度,我错过了日志并且总是读取 0 字节,尽管进程继续写入它。这是我的阅读器子,一段时间后,Dim n As Integer = stream.Read(bytes, numBytesRead, numBytesToRead)行总是给出 0:
Public Function readFile(ByRef stream As FileStream) As String
Dim bytes() As Byte = New Byte((stream.Length) - 1) {}
Dim numBytesToRead As Integer = CType(stream.Length, Integer)
Dim numBytesRead As Integer = 0
While (numBytesToRead > 0)
' Read may return anything from 0 to numBytesToRead.
Dim n As Integer = stream.Read(bytes, numBytesRead, numBytesToRead)
' Break when the end of the file is reached.
If (n = 0) Then
Exit While
End If
numBytesRead = (numBytesRead + n)
numBytesToRead = (numBytesToRead - n)
End While
numBytesToRead = bytes.Length
Return Encoding.UTF8.GetString(bytes)
End Function
流参数是一个全局变量(对主 Winform 来说是全局的),声明为:
Private FSReaderLog As FileStream
并初始化(仅在表单加载中)如下所示,打开流和中继文件内容:
Public Function InitLog(ByVal ruta_fichero As String) As FileStream
Dim FS As New FileStream(ruta_fichero, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
FS.SetLength(0)
FS.Flush()
Return FS
End Function
读者有什么问题?
谢谢