캐시 파일 읽기 및 쓰기를 처리하는 라이브러리가 있습니다. 이 라이브러리는 Windows 서비스 및 동일한 시스템의 콘솔 응용 프로그램 인스턴스에서 사용됩니다. 사용자가 로그인하면 콘솔 응용 프로그램이 실행됩니다.C# IO 읽기 및 쓰기 file in use 오류
캐시 파일이 다른 프로세스에서 사용 중임을 알리는 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;
}
}
}
+1 : 이것은 OP가 필요로하는 것과 정확히 같습니다. 실제로,'StreamWriter' 클래스의 MSDN은 스레드 안전 출력이 필요할 경우'StreamWriter'를'TextWriter.Synchronized'로 대체 할 것을 명시 적으로 제안합니다. – Brian
동기화는 정적 방법입니다. –
이 작업은 * in-process * 동기화에서만 작동합니다. 질문은 실제로 * 프로세스 간 * 동기화에 관한 것이며, 뮤텍스에만 OS 레벨 범위가 있습니다. – Aaronaught