如何使用filestream / streamwriter处理并发文件访问? [英] How to handle concurrent file access with a filestream/streamwriter?
问题描述
我正在写一个审计文件,它正在为每个用户在使用我的应用程序时写入应用程序中的几个变量的用户名,时间和旧的/更改的值。它使用 FileStream
和 StreamWriter
访问审计文件。每个用户的所有审计将写入同一个文件。
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
这存在于一个AuditLogger类中,该类通过一个实例变量引用(每次访问该函数时重新分配)。
This lives in an AuditLogger class, which is referenced via an instance variable (re-allocated each time the function is accessed).
推荐答案
重构应用程序,以便您不必创建 AuditLogger
类的新实例每一次。直接使用单一模式,或使用 dependency-injection 框架在整个应用程序中使用相同的实例。
Refactor the application so that you do not have to create a new instance of the AuditLogger
class each time. Use the singleton pattern directly, or a dependency-injection framework to use the same instance throughout the application.
从这里,实现更容易:用 lock
语句包围写操作,或使用 TextWriter.Synchronized
From there, the implementation is much easier: surround the write operations with lock
statements, or use the TextWriter.Synchronized
as has been mentioned in Robert's answer.
此帖可能与以下相关:
- Dependency injection and logging interfaces
这篇关于如何使用filestream / streamwriter处理并发文件访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!