在多线程应用程序中写入文件失败vb.net

Smi*_*ith 2 vb.net io multithreading streamwriter winforms

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

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
Run Code Online (Sandbox Code Playgroud)

我得到的错误消息

该进程无法访问文件'error.log',因为它正由另一个进程使用.

我可以通过哪种方式使其安全?

Han*_*ant 6

    Dim objLock As New Object
Run Code Online (Sandbox Code Playgroud)

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