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

发布于 2024-11-19 15:49:53 字数 1003 浏览 1 评论 0原文

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萝莉病 2024-11-26 15:49:54
    Dim objLock As New Object

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

    Dim objLock As New Object

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文