【问题标题】:writing to file in multithreaded app fails vb.net在多线程应用程序中写入文件失败 vb.net
【发布时间】: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


【解决方案1】:
    Dim objLock As New Object

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

【讨论】:

  • 感谢回复,此代码在模块中,您的解决方案是否仍然适用?
  • 您会自动获得共享。您确实需要自己创建 objLock,使用 As New 还不够好。在任何线程启动之前运行的代码中执行此操作。
猜你喜欢
  • 2023-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多