Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top