C# 自动保存清理;最佳实践?

发布于 2024-08-12 00:16:00 字数 476 浏览 3 评论 0原文

我有一个代表文档的类(GH_Document)。 GH_Document 有一个 AutoSave 方法,该方法在每个潜在危险操作之前调用。此方法会在原始文件旁边创建(或覆盖)一个自动保存文件。

GH_Document 还包含一个名为 DestroyAutoSaveFiles() 的方法,该方法从磁盘中删除由 AutoSave 函数创建的所有文件。当应用程序关闭以及卸载文档时,我会在文档上调用此方法。然而,我似乎错过了一些情况,因为在一些成功关闭后自动保存文件仍然存在。

这让我开始思考。处理这种情况的最佳方法是什么?我是否应该追踪文档消失的所有可能方式并在各处添加自动保存清理逻辑?或者我应该实现 IDisposable 并在 GH_Document.Dispose() 中执行清理?或者我应该在 GH_Document.Finalize() 中执行此操作?

我希望自动保存文件保留在磁盘上的唯一时间是应用程序崩溃时。是否保证在崩溃时不会调用 Dispose 和 Finalize?

I've got a class that represents a document (GH_Document). GH_Document has an AutoSave method on it which is called prior to every potentially dangerous operation. This method creates (or overwrites) an AutoSave file next to the original file.

GH_Document also contains a method called DestroyAutoSaveFiles() which removes any and all files from the disk that have been created by the AutoSave function. I call this method on documents when the app closes down, and also when documents get unloaded. However, it appears I missed a few cases since AutoSave files are still present after some successful shutdowns.

So this got me thinking. What's the best way to handle situations like this? Should I track down all possible ways in which documents can disappear and add autosave cleanup logic everywhere? Or should I implement IDisposable and perform cleanup in GH_Document.Dispose()? Or should I do this in GH_Document.Finalize()?

The only time I want an autosave file to remain on disk is if the application crashes. Are Dispose and Finalize guaranteed to not be called in the event of a crash?

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

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

发布评论

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

评论(1

转身以后 2024-08-19 00:16:00

是否保证在崩溃时不会调用 Dispose 和 Finalize?

一般来说,不会,尽管这取决于应用程序崩溃的方式。在 C# 中,它通常是未捕获的异常传播到顶层的结果。在这种情况下,任何finally子句都将在堆栈上执行,其中包括来自using语句的Dispose调用。

如果应用程序突然终止(例如在任务管理器中终止它),finally 子句将不会被调用,但您不应该依赖此行为。

一个简单的解决方案是将自动保存文件放入具有特殊命名约定的隐藏目录中,并在成功关闭时删除该目录中的所有自动保存文件。

Are Dispose and Finalize guaranteed to not be called in the event of a crash?

In general, no, although it depends on how your application crashes. In C# it will usually be the result of an uncaught exception propagating up to the top level. In this case, any finally clauses will be executed on the way up the stack, and that includes Dispose calls from using statements.

If the application is terminated suddenly (for example by killing it in Task Manager) the finally clauses will not be called, but you shouldn't rely on this behaviour.

A simple solution is to put your auto save files in a hidden directory with a special naming convention and delete all autosave files in that directory on successful shutdown.

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