我有一个处理缓存文件读写的库。此库由 Windows 服务和同一台计算机上的控制台应用程序的多个实例使用。控制台应用程序在用户登录时运行。
我偶尔会收到 IO 错误,提示缓存文件正在被另一个进程使用。我假设在尝试同时读取和写入的不同应用程序实例和服务之间发生了冲突。
有没有办法在文件正在使用时锁定文件并强制所有其他请求“排队等待”以访问该文件?
private void SaveCacheToDisk(WindowsUser user) {
string serializedCache = SerializeCache(_cache);
//encryt
serializedCache = AES.Encrypt(serializedCache);
string path = user == null ? ApplicationHelper.CacheDiskPath() :
_registry.GetCachePath(user);
string appdata = user == null ? ApplicationHelper.ClientApplicationDataFolder() :
_registry.GetApplicationDataPath(user);
if (Directory.Exists(appdata) == false) {
Directory.CreateDirectory(appdata);
}
if (File.Exists(path) == false) {
using (FileStream stream = File.Create(path)) { }
}
using (FileStream stream = File.Open(path, FileMode.Truncate)) {
using (StreamWriter writer = new StreamWriter(stream)) {
writer.Write(serializedCache);
}
}
}
private string ReadCacheFromDisk(WindowsUser user) {
//cache file path
string path = user == null ? ApplicationHelper.CacheDiskPath() :
_registry.GetCachePath(user);
using (FileStream stream = File.Open(path, FileMode.Open)) {
using (StreamReader reader = new StreamReader(stream)) {
string serializedCache = reader.ReadToEnd();
//decrypt
serializedCache = AES.Decrypt(serializedCache);
return serializedCache;
}
}
}
最佳答案
当然,您可以使用 mutex并仅在持有互斥量时允许访问。
关于C# IO Reading and Writing file in use 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2297067/