I am writing an audit file that is writing the username, time, and the old/changed values of several variables in the application for each user when they use my application. It is using a FileStream
and StreamWriter
to access the audit file. All audits for each user will be written to the same file.
The issue is that when two users are updating this audit file at the same time, the "old value" of each of the variable is mixing up between the users. Why is this and how can you solve the concurrency problem here?
Some code, shortened for brevity...
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
This lives in an AuditLogger class, which is referenced via an instance variable (re-allocated each time the function is accessed).