Aug 16, 2010

Save user settings on exit

Do you use a Settings file with your Windows Forms application to store user settings like preferences? Would you like it to save those settings to disk after the program closes? Just add the following line to your Main method:

Application.ApplicationExit += new EventHandler(Application_SaveSettingsOnExit);

And implement a method like the following:

static void Application_SaveSettingsOnExit(object sender, EventArgs e)
    Thread t1 = new Thread(new ThreadStart(Properties.User.Default.Save));
    t1.Name = "OnExit";
    t1.IsBackground = false;

The key is setting IsBackground to false. By doing this, we're saying that the thread we're kicking off is a foreground thread. This will prevent the process from exiting until that thread exits (i.e. finishes). If you don't do that, the call by Windows to exit the process will kill background threads instead of waiting on them.

Obviously, you can customize this to suit your needs. Saving manually (the OK/Apply button in your Options dialog, perhaps?) or more often automatically might be good practice, too. This is just a really simple example.

No comments:

Post a Comment