I have a .Net application that uses their user settings. What is the best time to save these settings?
To be clear, I’m calling this function to save the:
Storage.Properties.Settings.Default.Save()
First, I though to save them on every change, but that’s slow, and don’t seem to be necessary. The documentation suggest that they only need to be saved when the application is closing, in in their example, when a form is closing.
But, what if there are two instances of the application running? It seems that if I wait until Application_Exit event, the settings won’t persist between the instances. The new instance of the application would read the old user settings, causing an error.
So, what’s the best practice for this?
The answer is application specific, so there is no best practice. Some apps don’t even allow multiple instances, for example.
But most apps tend to do one of these things:
The problem with saving on exit is that your changes may be lost when you have a bug that causes an unhandled exception. If your app is supposed to run in the background, this might happen more often than you think, especially while it is still in development/testing.
I went with a “save on exit” strategy with a toy system-tray style app I wrote several years back, and regretted it. Explicit saves and/or interval saves would have been a much better option.