开发者

writing to file in multithreaded app fails vb.net

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 savin开发者_StackOverflow中文版g", _
                                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?


    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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜