The best shutdown sequence for an application is the shutdown sequence that doesn’t require any work.
If all resources held by your application are process-wide resources that do not affect the rest of the system, then your shutdown sequence doesn’t require any work. All you need to do is let the system close you down.
Many resources fit in this category – memory, for one, is something that you shouldn’t be obsessively freeing when asked to shutdown. Windows will reclaim the memory, don’t worry about it. Handles to kernel objects are another example, although some of them don’t like being abandoned (e.g. mutex handles would rather be closed or released than abandoned in mid-acquire). Database connections, on the other hand, represent a resource that might take some time until it’s reclaimed by a timeout.
The primary reason for minimizing the shutdown sequence as much as possible is fairly simple. If your application hasn’t been used for quite a while, then your shutdown sequence might result in lots and lots of paging. There are myriads of applications that take a long time to shut down, and the disk LED starts flashing repeatedly for several minutes. During the process, you’re paging in memory that is completely useless (strictly speaking, it’s needed for your shutdown sequence, but…) and you’re causing other memory that is useful to be paged out, effectively incurring yet another series of paging activity when your application has finally been closed.
But why would the user close your application after it hasn’t been used? I hope you’re not asking this question, but just in case you are, here are some common reasons:
- The system has just come out of standby or hibernation, and the user wants to shut down or restart the system.
- The user has just finished watching three consecutive episodes of his favorite TV show, and while going to bed decided to shut down the computer.
- The user has just finished reading his 300-message email backlog, with your application in the background, and now wants to shut down the system and go to bed.
- The user has been prompted with some Windows Updates installation, and during the process was incapable of using the system. Now that updates have completed, the user wants to restart the system.
Wrapping up this short piece of advice: Don’t start freeing memory and obsessively validating resources when the user has requested a shutdown. If your application hasn’t been used for a while, you’re now paging the entire world back in from the disk. Do the bare minimum and get out!