Win32: Non-responsive Threads

Mon, 28 Jan 2008 23:42:51 -0500 - Author:

A thread is non-reponsive ("Not Responding") if it has not called SendMessage, WaitMessage,GetMessage or PeekMessage within the past five seconds. Some people call non-responsive threads as "hung" threads. Normally you check if a thread is hung to determine whether it's best to send a message to a thread, or when terminating an application. Every five seconds, Task Manager walks its list of task windows and makes the following call for each window:

  DWORD dwResult; 
 BOOL fResponding = SendMessageTimeout(hwndInQuestion, 
      WM_NULL, 0, 0, SMTO_ABORTIFHUNG, 5000, &dwResult);        
Task Manager sends the WM_NULL message (should be a useless message) to the window. If the window's thread is determined to be already "hung" or the timeout of 5000 milliseconds expires before the message is fully processed, SendMessageTimeout returns FALSE and the window's thread is considered non-responsive.

Alternatively, there are undocumented APIs for determining the responsive status of a thread. In 95/98 it is called IsHungThread, and in NT it's called IsHungAppWindow. Both functions are exported in User32.dll, but they can't be found in the respective library file. To access them, dynamically load them in your program. The function below, IsWindowHung, implements these undocumented functions.


typedef BOOL (*tIsHungAppWindow)(HWND);
typedef BOOL (*tIsHungThread)(DWORD);


BOOL IsWindowHung(HWND hwnd){
 WORD ver=HIWORD(MyGetVersion());
 HMODULE hmod=GetModuleHandle("User32.DLL");
 if(ver==VER_PLATFORM_WIN32_NT){
  tIsHungAppWindow func;
  func=GetProcAddress(hmod,"IsHungAppWindow");
  if(!func)return TRUE; // assume window is not hung
  return func(hwnd);
 } else {
  tIsHungThread func;
  func=GetProcAddress(hmod,"IsHungThread");
  if(!func)return TRUE; // assume window is not hung
  return func(GetWindowThreadProcessId(hwnd,NULL));
 }
 return TRUE;
}

One final note: You shouldn't consider threads without windows as hung because most likely it's doing beneficial background processing for an application.