Is my application’s UI still responsive ?

We might, on occasion, need to check whether an application we’ve spawned has a responsive UI or ofcourse we might wish to check our own application, for example within a timer polling the following code to check the application is still responsive.

Firstly, we could use the property Responding on the Process class which allows us to check whether a process’s UI is responsive.

Process p = Process.Start("SomeApplication.exe");

if(!p.Responding)
{
   // the application's ui is not responding
}

// on the currently running application we might use 

if(!Process.GetCurrentProcess().Responding)
{
   // the application's ui is not responding
}

Alternatively we could use the following code, which allows us to set a timeout value

public static class Responsive
{
   /// <summary>
   /// Tests whether the object (passed via the ISynchronizeInvoke interface) 
   /// is responding in a predetermined timescale (the timeout). 
   /// </summary>
   /// <param name="si">An object that supports ISynchronizeInvoke such 
   /// as a control or form</param>
   /// <param name="timeout">The timeout in milliseconds to wait for a response 
   /// from the UI</param>
   /// <returns>True if the UI is responding within the timeout else false.</returns>
   public static bool Test(ISynchronizeInvoke si, int timeout)
   {
      if (si == null)
      {
         return false;
      }
      ManualResetEvent ev = new ManualResetEvent(false);
      si.BeginInvoke((Action)(() => ev.Set()), null);
      return ev.WaitOne(timeout,false);
   }
}

In usage we might write the following

if (IsHandleCreated)
{
   if (!Responsive.Test(this, reponseTestDelay))
   {
       // the application's ui is not responding
   }
}