Window Hangs


A window hang in the context of Win32 is an HWND that has not yet processed one or more messages targetted to it.  For example, clicking a button on a window sends a message to the WNDPROC associated with that window.  If the thread is busy doing something else, that message does not get serviced and the user experiences a window hang.


When a thread creates a window (i.e., through the API CreateWindow), it has entered into a contract with Windows whereby the thread must respond to messages generated for the window.  To do so, the thread must periodically and continuously yield control to Windows to handle this servicing – also known as “Pumping The Message Queue”.


When using Vista or Windows 7, you may have noticed a window become unresponsive and shortly thereafter, it started to look like a “frosted” version of itself.  The text on the title bar for these applications has the phrase “(Not Responding)” appended to it:


Hung Application


This condition is called a Window Hang.  Some applications are more prone to a Window Hang than others, and it’s simply a matter of whether the code is built to be responsive.


Here is a simple example of code that produces a Window Hang:


LRESULT CALLBACK MyWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
        // …


        case WM_COMMAND:
            // …

            Sleep(INFINITE);
            break;
    }
}


However, it is rare for people to write code like this.  The following unsuspecting code is much more prevalent in causing hangs:


LRESULT CALLBACK MyWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
        // …


        case WM_COMMAND:
            // …

            CreateFile(…);
            break;
    }
}


The CreateFile call used here will induce I/O from within the WNDPROC.  While your unit tests for this may not produce a hang, it can likely lead to a hang some day.  The responsiveness of I/O is not predictable in practical terms.


Comments (0)

Skip to main content