我有一个将日志写入文件的多线程应用程序。偶尔,使用此代码保存失败

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 process cannot access the file 'error.log' because it is being used by another process.

还有什么其他方法可以保证安全?

请您参考如下方法:

    Dim objLock As New Object 

您的 SyncLock 语句不会锁定任何内容。每个线程都将获得自己的 objLock 实例,因为它是一个局部变量,每次进入方法时都会分配。将声明移到方法之外,使其成为您的类的成员。并确保该类只有一个实例。或者将其设为共享只读。


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!