简体   繁体   English

如果多个用户同时调用 C# File.WriteAllText 到同一位置会发生什么?

[英]what happens if multiple users call C# File.WriteAllText at the same time to the same location?

tldr; tldr; If multiple users/instances of an application call File.WriteAllText() to the same filepath at the same time, what will happen?如果一个应用程序的多个用户/实例同时调用 File.WriteAllText() 到同一个文件路径,会发生什么? will the call throw an exception, will the call throw an exception and corrupt the file, will the call 'succeed' but still potentially corrupt the file, will the OS schedule one to happen after the other or will some other thing happen?调用是否会引发异常,调用是否会引发异常并损坏文件,调用是否会“成功”但仍可能会损坏文件,操作系统会安排一个接一个发生还是会发生其他事情?

We have an application that saves config settings each time they use our application's main feature.我们有一个应用程序,每次他们使用我们应用程序的主要功能时都会保存配置设置。 The config is saved to the app's install folder, to the same path each time.配置保存到应用程序的安装文件夹,每次都保存到相同的路径。 We now have a client that wants to have multiple users running the application from the same install path.我们现在有一个客户端,它希望多个用户从同一安装路径运行应用程序。 If a conflict results in the config not saving that's not an issue, but if the conflict results in corruption it would be inconvenient.如果冲突导致配置不保存,那不是问题,但如果冲突导致损坏,那就不方便了。 I just need to know the likelihood of the call corrupting the file and not throwing an error?我只需要知道调用损坏文件而不抛出错误的可能性吗?

Any help or links to sources would be greatly appreciated, I couldn't find anything when I was looking.任何帮助或来源链接将不胜感激,我在寻找时找不到任何东西。

Thanks in advance提前致谢

Edit: With FileStream, and with FileShare.Read, if another user tries to read the file in the middle of a write, will he get the earlier version of the file?编辑:使用 FileStream 和 FileShare.Read,如果另一个用户尝试在写入过程中读取文件,他会得到文件的早期版本吗? or will he get an incomplete file?还是他会得到一个不完整的文件? this is not a large file being written, but would it be necessary to set it to FileShare.None and add retries to the file.read as well or not?这不是一个正在写入的大文件,但是否有必要将其设置为 FileShare.None 并向 file.read 添加重试?

It turns out it produces an exception (I ran four instances of the application and closed them all at the same time, all but one threw an exception), File.WriteAllText() appears to lock the file.事实证明它产生了一个异常(我运行了四个应用程序实例并同时关闭了它们,除了一个之外都抛出了异常),File.WriteAllText() 似乎锁定了文件。 Just to be safe though, FileStream seems to give the ability to do this explicitly不过为了安全起见, FileStream 似乎提供了明确执行此操作的能力

using (FileStream writer = new FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.Read)) {
    writer.Write(jsonString));
    writer.Flush();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM