我正在编写一个审计文件,该文件在每个用户使用我的应用程序时为每个用户编写用户名、时间和应用程序中几个变量的旧/更改值。它使用FileStream
andStreamWriter
来访问审计文件。每个用户的所有审核都将写入同一个文件。
问题是当两个用户同时更新此审计文件时,每个变量的“旧值”在用户之间混合。为什么会这样,如何解决这里的并发问题?
一些代码,为了简洁而缩短......
Dim fs As FileStream
Dim w As StreamWriter
Public Sub WriteAudit(ByVal filename As String, ByVal username As String, ByVal oldAddress As String, ByVal newAddress As String, ByVal oldCity As String, ByVal newCity As String)
Dim now As DateTime = DateTime.Now
Dim audit As String = ""
audit += now + "," + username + "," + oldAddress + "," + newAddress + "," + oldCity + "," + newCity
fs = New FileStream(filename, FileMode.Append)
w = New StreamWriter(fs)
w.WriteLine(audit)
w.Close()
fs.Close()
End Sub
这存在于 AuditLogger 类中,该类通过实例变量引用(每次访问函数时重新分配)。