A brief discussion on how best to respond to the end-session messages

A customer discovered that their application's shutdown code sometimes deadlocked. To address the problem, they moved the bulk of their shutdown code to the WM_END­SESSION message handler. The customer found my earlier discussion of the WM_END­SESSION message and wondered if they were doing the right thing.

Yes, it's okay to do shutdown activities in response to the WM_END­SESSION message, provided that the wParam is nonzero, indicating that the session really is ending. If the wParam is zero, then it means that the session is not ending, so you had better not destroy anything you still need.

Recall the shutdown sequence: First, the application receives a WM_QUERY­END­SESSION message. Here is the traditional point at which you can display a prompt to ask the user whether they want to save their unsaved changes.¹ Normally, you return TRUE, but if the user hits Cancel or otherwise indicates that they don't want to shut down after all, then you return FALSE.

If you returned TRUE, then you will eventually receive a WM_END­SESSION message whose wParam indicates whether the session really is ending. (The session might not actually be ending if another application returned FALSE to the WM_QUERY­END­SESSION message, or if the user canceled shutdown from the UI.)

The customer shared some of their code, and I noticed that they were destroying a window in their WM_END­SESSION message handler, which is suspicious for two reasons:

  1. If the wParam is FALSE, the application will continue to run, but it lost one of its windows!
  2. If the wParam is TRUE, then it's okay to destroy things, but remember that you are running under a time constraint, and the building is being demolished, so you probably shouldn't be wasting time sweeping the floor and emptying the trash cans.

What you could do is to kick off a background thread to prepare for shutdown when you receive the WM_QUERY­END­SESSION message. For example, you might start an autosave operation. Whatever you do, make sure that it's okay for the operation to occur even if the shutdown is subsequently canceled.

When you get the WM_END­SESSION message, you wait until that background operation completes before telling the system, "I'm good; you can shut down now."

Opportunistically starting the operation when you get the WM_QUERY­END­SESSION message means that you can respond more quickly to the WM_END­SESSION message.

¹ In practice, displaying a prompt is usually not a good idea because if you don't respond to the message after a few seconds, the system will shut down without you.

Comments (25)
  1. Koro says:

    Doing an auto-save on end-session seems like the worst thing: what if the process gets killed midway through writing the file? Data loss.

    1. creaothceann says:

      @Koro: That’s why you use checksums and don’t automatically overwrite/delete old saves.

    2. I meant crash recovery autosave, the one you do in case the program crashes so that on restart you can say “Hey, sorry about the crash. Do you want to recover the unsaved document?” Get that thing all ready to go, and if the user decides “Why yes, please save,” you just do a little renaming.

  2. henke37 says:

    You’d think that Windows would let you expose to the system that there is unsaved changes and provide an unified interface in the shutdown screen to deal with the situation. It’s not a new situation.

    1. dhiren says:

      This is what I would love to see in the next Win10 update. What would be awesome would be if, instead of saying something like ‘this program is preventing you from shutting down’, it could say ‘this program has unsaved work’ with a Save button next to each blocking program.

      That way, I could save right from the shutdown screen, or click ‘Restart anyway’ or ‘Force Restart’ or whatever to discard the changes.

      If a program is blocking the shutdown for reasons other than a pending save, then the existing ‘this program is preventing you from shutting down’ message can be displayed, with a Review button that could switch back to the desktop, putting that window in focus. As soon as I resolve whatever’s blocking the shutdown, as soon as the blocking window is closed, switch back to the shutdown screen and continue with the shutdown.

      1. Electron Shepherd says:

        That sounds great, but I think the devil is in the details.

        Firstly, you’ll need that time machine that the guys at Microsoft Research have developed and make sure that existing software (e.g. the ever-popular Word 2007) knows about this new way to save documents.

        Then you have to worry about programs that have not yet saved their document, so you need to prompt the user for a location and filename. A previously saved document that can’t be re-saved (if it was saved to a now-removed USB stick), is a special case of this, but would also need handling.

        1. Dmitry says:

          Yeah, the current behavior is much better. Just kill all crap that is messing up on The Holy Update Reboot Trail. You know, “Reboot in 30 seconds” is the priority #1.

        2. dhiren says:

          Of course the actual implementation requirements would be a bit more than a few lines on a blog comment, but from a very end-user point of view, the obvious pitfalls that you mentioned are easily solved. Naturally, there would be various technical or back-compat reasons that things can’t be as simple in the end, but off-hand:
          – no time machine necessary – if the app doesn’t support the new functionality, it doesn’t get the new save button. Eventually (i.e. hopefully), most apps support the new functionality and everyone eventually (lol) upgrades to the newer versions.
          – if the user clicks Save but no existing filename is available, the app can request the shutdown screen to
          a) display a save dialog on its behalf, which would likely make for a messy UI/workflow, so instead, rather…
          b) fall back to the Review functionality, where we switch back to the desktop and focus the offending application, which would already most likely have its save dialog open already. Once the file’s been saved (or the save’s been cancelled) and the application closed, we go back to the shutdown screen
          c) in fact, when the app receives the shutdown notification, since it already knows that it doesn’t have an existing filename to save to, it can just decline the opportunity to display the save button, and just fall back to Review instead
          – if the app encounters an error while saving, fall back to the Review functionality

          The Review mode could be implemented such that if the user switches away from the program whose shutdown is being reviewed, then they just stay on the desktop and the shutdown is cancelled.

          (Yes, this is something I’m passionate about for no reason whatsoever)

          1. One of the tricky parts is knowing when the user has switched away from the program. There are common cases (e.g., editing an OLE embedding) where there are multiple processes all working together as one “app”. You are waiting for the user to save in program X, and they click a toolbar button – but wait, that toolbar button is running in program Y because it’s a plug-in, and now we think the user has canceled the save. I also wonder if people will like the bouncing between environments (shutdown screen and Review mode).

          2. ErikF says:

            Fast User Switching/Remote Desktop puts a whole bunch of wrenches in the works as well, because you may have programs on different desktops (with different credentials!) wanting to confirm; right now, Windows just lists which programs are being slow to quit. What do you do with those other programs? (I don’t think there is a good answer to this one, but maybe there is and I just can’t see it.)

          3. cheong00 says:

            Could it be desirable to add some flag in THUMBBUTTON for ITaskbarList3::ThumbBarAddButtons() so you could use as a button to be displayed on shutdown event if it waited for too long? In addition to the standard “force close” one.

        3. Deltics says:

          I don’t think the time machine they built is fit for purpose. Otherwise they wouldn’t be trying to sell it.


    2. 640k says:

      Actually, instead I, and probably most people, hope windows will be even more aggressive to shut down obstructing applications, and not display “these apps doesn’t respond” AT ALL. F*ck those apps. Instead apps should implement auto-recover, that will also improve the experience when (not if) those apps crash. If you’re work-flow include putting important stuff in notepad, tough luck. Learn to use a better app instead.

      1. Joshua says:

        The newer apps (surprisingly) have worse accessibility than the older ones.

      2. Antonio Rodríguez says:

        You’d be surprised to know how many users rely on the close unsaved document to actually save their work. It’s a really bad idea (move the mouse a bit, and the pointer ends on “No” instead of “Yes”, losing your work), and I try to explain them why it’s a bad idea; but even then, they keep doing it.
        Force close all apps, and you’d destroy many people’s work, and get many angry headlines shouting “Microsoft removes the save function on Windows 11!”.

      3. Antonio Rodríguez says:

        Also, force-closing apps is what you get when features are dictated by technical writers in magazine and blogs which rely more in chronometer times for startup, shutdown and install, instead on real usability questions (which, admittedly, can’t be measured objectively): a newer version of Windows can’t be any good if it takes more to start up or install than the previous one, no matter what features it introduces.
        Actual users, on the other hand, don’t mind if they have to shut down their computers ten minutes before leaving work (in fact, that allows them to stop working ten minutes earlier!). And they don’t care at all about install times, because they never have, and never will, install Windows at their machines – computer stores or IT personnel do that for them.

      4. Neil says:

        I wish Windows 10 wouldn’t close all my InPrivate windows and install updates automatically. (I don’t know how big the time window to spot the new updates available notification is but I missed it last month…)

        1. Neil says:

          Or maybe I’m just suffering from today’s XKCD: http://www.xkcd.com/1817/

      5. morlamweb says:

        “Actually, instead I, and probably most people, …”. Well, this right-thinking person would rather not have an overly aggressive shutdown, thanks. I’d actually rather have a chance to save any unsaved data before the system shuts down.

    3. ChDF T says:

      While this would be nice, it is not the simplest solution to this problem: When a user says “shutdown now” to the system (the “now” part is implicit, when they click the button), this guarantees you, that the user will not do anything with the document until he starts the computer again. That means, that it doesn’t matter if you ask them now or the next time they start your application. Ideally you already do the later in case the application exits unexpectedly (usually due to a crash), so that means no additional work – yay.
      This also moves the point of decision to a moment, where he has time to make an informed decision (because they see the document in question, can check timestamps in explorer, do whatever and are not in a hurry).

      Implementing such a “do you want to save?” would also make “saving” special. What if my application would like to ask the user something else on shutdown? What if one application has more than one document with unsaved changes? What if saving is not possible anymore because something needed for saving (like some service, other process, physical medium) is already gone/terminated? Asking this kind of question using already existing APIs on the next application start makes things a lot easier.

  3. I find the Vista and later fullscreen shutdown UI frustrating and usually disable it through group policy. I agree the previous policy where apps (even hidden) could prevent shutdown was frustrating but at least it allowed you to save your doc in notepad or whatever else you didn’t have saved. Now with the fullscreen shutdown UI, you’re told notepad is not responding but only have the choice of canceling shutdown or losing your data. Not very good choices.

    If MS really wants to developers to move to the autosave model they would lead the way with the builtin apps like notepad and paint.

  4. Adrian says:

    It would be cool to have a tool that simulates the various shutdown scenarios so that you can test how your apps responds without, you know, actually ending your session. The tool would send the victim app the WM_QUERYENDSESSION and WM_ENDSESSION messages with all the right parameters (in the same way the system would in a real shutdown) and then kill the app’s process immediately after returning from WM_ENDSESSION. Then restart the app and check your data recovery procedure.

    Yep. Sounds useful. I think I’ll go write that.

  5. Adrian says:

    What’s never been clear to me is what happens if the system is being shut down while the application is in a modal loop.

    I assume a top level window can receive WM_QUERYENDSESSION and WM_ENDSESSION while disabled, but what if the modal message loop is filtering messages and dispatching only to an owned window? I know these messages are “sent,” but they’re sent cross-process, which I assume relies on the receiver pumping messages to the target window.

    Perhaps that’s rare. The standard dialog loop doesn’t filter messages as far as I can tell, nor does the move/resize loop.

    But apps often rely on the assumption that modality is a rock-solid guarantee that nothing interesting will happen to the top level window. I can imagine all sorts of problems where an app deadlocks trying to do an emergency save of the document while in some modal state. I guess it’s the responsibility of the app to that no modal dialog or other model state could interfere with the ability to do an emergency save. That sounds hard to test.

  6. Andrei says:

    I’m wondering why Word 2016 is not doing like this. I clicked on Shut Down and left the PC, only to return in the morning to a PC hung in Word’s “There are unsaved files” or similar message.

Comments are closed.

Skip to main content