c# - 使用 System.IO.File 辅助方法的 "sequential"文件 I/O 是否安全?

标签 c# .net io

我刚看到这个问题:Is it safe to use static methods on File class in C#? .总而言之,OP 有一个 IOException,因为此 ASP.NET 代码片段中正在使用文件:

var text= File.ReadAllText("path-to-file.txt");
// Do something with text
File.WriteAllText("path-to-file.txt");

我的第一个想法是,由于多个 ASP.NET 重叠请求,这是一个简单并发访问问题。我要解决的问题是将 I/O 集中到一个同步的线程安全类中(或删除文件以支持其他内容)。我阅读了这两个答案,当我正要对其中一个投反对票时,我看到了那些用户是谁,我想 他妈的 然后停了下来。

我会引用它们(然后请引用原始答案以获取更多上下文)。

对于这个 OP 段落:

I am guessing that the file read operation sometimes is not closing the file before the write operation happens [...]

一个回答说:

Correct. File systems do not support atomic updates well [...] Using FileStream does not help [...] File has no magic inside. It just uses FileStream wrapped for your convenience.

但是我看不到原子操作(读取 + 后续写入)有任何期望,并行(因为部分重叠的多线程请求)可能会导致并发访问。即使是原子 I/O 操作(读+写)也会有完全相同的问题。好的 FileStream 可能 是异步的,但这不是 File.ReadAllText()File.WriteAllText() 使用它的方式.

另一个答案让我更加困惑,它说:

Although according to the documentation the file handle is guaranteed to be closed by this method, even if exceptions are raised, the timing of the closing is not guaranteed to happen before the method returns: the closing could be done asynchronously.

什么? MSDN 说方法将打开、读取和关闭文件(在出现异常的情况下也是如此)。这种方法是否有可能异步关闭文件?操作系统会延迟 CloseHandle() 吗?在哪些情况下?为什么?

简而言之:是误会还是CloseHandle()是异步的?我遗漏了一些极其重要的东西?

最佳答案

如果您查看 CloseHandle文档中,它指出每个打开句柄的方法都有关于如何关闭它的描述:

The documentation for the functions that create these objects indicates that CloseHandle should be used when you are finished with the object, and what happens to pending operations on the object after the handle is closed. In general, CloseHandle invalidates the specified object handle, decrements the object's handle count, and performs object retention checks. After the last handle to an object is closed, the object is removed from the system.

当您查看 CreateFile文档,这就是它所说的:

When an application is finished using the object handle returned by CreateFile, use the CloseHandle function to close the handle. This not only frees up system resources, but can have wider influence on things like sharing the file or device and committing data to disk.

我会发现 CloseHandle 会导致底层句柄关闭,同时异步保留文件以进行额外检查,这很奇怪。这会削弱操作系统对调用者的许多保证,并且会成为许多错误的来源。

关于c# - 使用 System.IO.File 辅助方法的 "sequential"文件 I/O 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32433630/

相关文章:

c - 如何在 C 中将两个文本文件中的差异写入另一个文本文件?

c# - 如何检查 .NET 中是否存在文化

c# - 如何从字典列表中删除特定元素

c# - 具有一对一关系的 EF Core 批量插入

.net - 当我将变量设置为新对象时,旧值会消失吗?

c# - 重新分配单元格值后 Excel 公式丢失

c# - 在 CheckAccessCore 之后,WCF Access Denied 异常永远不会返回到客户端

.net - 使用派生列进行 SSIS 查找?

java - 如何在 Java 中指定文件的路径?

java - 使用 Spring 应用程序配置日志