在多线程应用程序中写入文件失败vb.net
我有一个将日志写入文件的多线程应用程序。有时,使用此代码保存失败
Friend Sub SaveToText(ByVal FileName As String, ByVal Text As String)
'// create a writer and open the file
Dim objLock As New Object
SyncLock objLock
Dim tw As TextWriter = Nothing
Try
'// write a line of text to the file
tw = New StreamWriter(FileName, True)
tw.Write(Text)
Catch ex As Exception
MessageBox.Show(ex.Message, "Error saving", _
MessageBoxButtons.OK, _
MessageBoxIcon.Error)
Finally
'// close the stream
If tw IsNot Nothing Then
tw.Close()
tw.Dispose()
End If
End Try
End SyncLock
End Sub
我收到的错误消息
该进程无法访问文件“error.log”,因为它正在被访问 被另一个进程使用。
还有什么其他方法可以保证安全?
I have a multi threaded app that writes log to file. occasionaly, saving fails using this code
Friend Sub SaveToText(ByVal FileName As String, ByVal Text As String)
'// create a writer and open the file
Dim objLock As New Object
SyncLock objLock
Dim tw As TextWriter = Nothing
Try
'// write a line of text to the file
tw = New StreamWriter(FileName, True)
tw.Write(Text)
Catch ex As Exception
MessageBox.Show(ex.Message, "Error saving", _
MessageBoxButtons.OK, _
MessageBoxIcon.Error)
Finally
'// close the stream
If tw IsNot Nothing Then
tw.Close()
tw.Dispose()
End If
End Try
End SyncLock
End Sub
The error message i get
The process cannot access the file 'error.log' because it is being
used by another process.
Which other way can i make this safe?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的 SyncLock 语句不会锁定任何内容。每个线程都会获得自己的 objLock 实例,因为它是一个局部变量,并且每次进入该方法时都会被分配。将声明移到方法之外,使其成为类的成员。并确保该类只有一个实例。或者将其设为共享只读。
Your SyncLock statement doesn't lock anything. Every thread will gets its own instance of objLock since it is a local variable and gets allocated every time the method is entered. Move the declaration outside of the method so it becomes a member of your class. And make sure there is only one instance of that class. Or make it Shared ReadOnly.