假设我有一些代码可以做到这一点:
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
这就是不到一半代码的所有功能。唯一的区别是您必须在调用代码中处理异常而不是检查返回状态。
关于.net - 将频繁的文件 I/O 操作放在 SyncLock 块中是一个坏主意吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1423049/