views:

268

answers:

1

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?

+1  A: 

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.

Mark Byers
Thanks Mark, that pretty much rules out the Finalize approach. My app runs as a managed plugin within an unmanaged environment and most crashes occur due to unhandled C++ exceptions, memory overflows or managed exceptions which in turn cause the base app to crash.I cannot destroy ALL autosave files, as people may be running more than one instance of my app, and one instance should not delete autosave files from another. Also, people won't be able to find this 'special' folder, it would put an extra burden on support. I think I'll just have to make the cleanup watertight.
David Rutten