【发布时间】:2011-10-03 02:24:06
【问题描述】:
我有一个将日志写入文件的多线程应用程序。有时,使用此代码保存会失败
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”,因为它正在 被另一个进程使用。
我还有什么方法可以保证这个安全?
【问题讨论】:
-
还有哪些进程会锁定该文件?你的病毒扫描程序?你的程序的另一个副本?不同的程序?
标签: vb.net winforms multithreading io streamwriter