.NET 下的 File.Delete() 是原子的吗

发布于 2024-08-20 18:56:01 字数 162 浏览 9 评论 0原文

目标操作系统:Win2003

正如在有关文件操作原子性的其他 SO 问题中发布的那样,Win32 根本不是为事务设计的。我仍然想知道文件删除是否可以是非原子的。毕竟,要么被删除,要么不被删除。或者,在删除过程中,由于系统崩溃或其他原因,文件是否可以在 NTFS 文件系统上保留任何其他中间状态?

Target OS: Win2003

As posted in other SO questions about file operation atomicity, Win32 was simply not designed for transactions. Still I wonder whether file deletion could be non-atomic. After all, it is either get deleted or not. Or can a file remain in any other intermediate state on NTFS file system caused by a system crash or something else during deletion?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小梨窩很甜 2024-08-27 18:56:01

NTFS 是一个日志文件系统。日志基本上相当于数据库中的事务日志。它将确保文件系统结构的一致性和完整性,就像数据库对其表所做的那样。虽然 File.Delete 没有任何高层事务代码,但 NTFS 确实在文件系统级别维护事务完整性。对于其他文件系统驱动程序来说可能并非如此。

NTFS is a journaled file system. A journal is basically equivalent to a transaction log in a database. It'll ensure consistency and integrity of the file system structures like a database does for its tables. While File.Delete doesn't have any transactional code at the high level, NTFS does maintain transactional integrity at the filesystem level. This may not be true for other file system drivers.

夜灵血窟げ 2024-08-27 18:56:01

老问题,但如果我可以从稍微不同的角度添加@Mehdrad的答案...

在Windows上,删除文件通常甚至不是完全同步的,而且它甚至不是单个操作。从这个意义上说,它绝对不是原子的。

如果您查看进程监视器等工具或查看有关编写文件系统的 MSFT 文档驱动程序后,您会注意到在 Windows 上删除文件是一个多步骤的过程。首先,您需要一个文件句柄。然后将其处置设置为“已删除”。这会将文件置于“待删除”状态。在关闭该文件的最后一个句柄之前,该文件甚至不会从视图中删除。当文件处于此状态时,打开该文件的新尝试将失败,并显示 STATUS_DELETE_PENDING。此状态更多的是运行时的情况 - 如果您拔掉插头或重新启动,文件将不会保持该状态。

因此,它可能与您使用删除的方式相关,也可能无关,但请务必记住,在 Windows 上,删除不一定会立即生效,并且在并发访问下可能会锁定进一步的请求,使其无法访问文件。

Old question, but if I could add to @Mehdrad's answer, from a slightly different standpoint...

On Windows, deleting a file often isn't even completely synchronous, and it isn't even a single operation. In that sense it's definitely not atomic.

If you look at tools like process monitor or look at MSFT documentation for writing a filesystem driver, you'll notice that to delete a file on Windows is a multi-step process. First you need a handle to the file. Then you set its disposition to "deleted". This puts the file in a state where it has a "delete pending". The file won't even be removed from view until the last handle to it is closed. When a file is in this state, new attempts to open the file will fail with STATUS_DELETE_PENDING. This status is more of a runtime thing -- if you pulled the plug or did a reboot the files won't stay in that state.

So, it may or may not be relevant to the way you're using deletes, but it's important to keep in mind that on Windows a delete won't necessary take effect right away and under concurrent access may lock further requests out of getting to the file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文