C#IO读取和写入文件正在使用错误

mod*_*bie 2 c# file-io

我有一个库来处理读取和写入缓存文件.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;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

jas*_*son 5

当然,您可以使用互斥锁,只有在持有互斥锁时才允许访问.