title: How can I cancel a hung Task?
body: <p>We have a Windows service that calls a 3rd party method that can hang when improperly configured by the end user, which is difficult to test for beforehand. We're handling this risk by calling the method in a Task with a timeout:</p>
  
  <pre><code>private int? FooWithTimeout()
  {
      var timeout = TimeSpan.FromMinutes(1);
      var task = Task.Run(Foo);
  
      if (!task.Wait(timeout))
      {
          Log("Foo timed out...");
          return null;
      }
  
      if (task.IsFaulted)
      {
          Log("Foo threw an exception...");
          return null;
      }
  
      return task.Result;
  }
  </code></pre>
  
  <p>The 3rd party method blocks forever waiting for input from a resource that cannot respond. It does <strong>not</strong> support cancellation in any way, shape, or form, nor does it have a built-in timeout. Our concern is that as the service runs these tasks will continue blocking and slowly accumulate, eventually consuming a large amount of resources.</p>
  
  <p>Is that a valid concern? Do we need to abort/dispose the tasks in some way? If so, what is the correct way to do so?</p>
  
  <p><em>Addendum:</em> The 3rd party in question is Crystal Reports. It hangs when asked to print to a printer that requires some sort of additional input from the user (for example, Microsoft XPS Document Writer will prompt you for where to save the file if you print to it). And by hang, I mean it attempts to show a user prompt to get the additional input, but it's in a Windows Service so nobody ever sees the user prompt and it waits forever for a human being to tell it how to print. We allow end users to configure which printer the service attempts to print to, and there isn't really any way to tell if a given printer requires additional input short of attempting to print to it.</p>