说我有一些代码可以做到这一点:
Public Function AppendToLogFile(ByVal s As String) As Boolean Dim success As Boolean = True Dim fs As IO.FileStream = nothing Dim sw As IO.StreamWriter = nothing Static LogFileLock As New Object() SyncLock LogFileLock Try fs = New IO.FileStream(LogFilePath) sw = New IO.StreamWriter(fs) sw.WriteLine(s) Catch ex As Exception success = False Finally If Not sw Is nothing Then sw.Close() If Not fs Is nothing Then fs.Close() End Try End SyncLock Return success End Function
首先:我在SyncLock中有Try / Catch / Finally块是一个问题吗?
第二个:假设这个代码在一个事件上运行,可能在很短的时间内运行很多次 – 比如说,在一秒钟内运行十次.让它像这样的SyncLock是否可以,或者让它在队列中添加一行更有意义,然后将所有行从队列写入到计时器上的文件,例如,每秒一次?
解决方法
乍一看,这看起来还不错,有两点需要注意:
>静态成员已在幕后使用一种线程安全锁定.因此,您可能只需要在现有锁上捎带,而不是显式锁定.不过,我不确定那会是什么样子.
>不要返回状态代码.让异常传播到适当的级别.完成后,您可以像这样重写代码:
.
Public Sub AppendToLogFile(ByVal s As String) As Boolean Static LogFileLock As New Object() SyncLock LogFileLock Using sw As New IO.StreamWriter(LogFilePath) sw.WriteLine(s) End Using End SyncLock End Sub