我有一个程序,其中有几个并行进程写入日志文件,主程序也在读取日志并将其汇集到文本字段。
事情是,达到某一点,我错过了日志并始终读取0字节,尽管进程一直在写它。这是我的reader sub,经过一段时间后,行 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
stream 参数是一个全局变量(主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
读者可能出现什么问题?
谢谢