title: How to timeout a blocking call to unmanaged code (.NET)?
body: <p>I have a call to an unmanaged code library that hangs if passed an incorrect parameter.</p>
  
  <pre><code>IWorkspaceFactory workspaceFactory = _workspaceFactory.OpenFromString(connectionString);
  </code></pre>
  
  <p>If <em>connectionString</em> has an invalid value, then <em>OpenFromString</em> hangs. If I break execution, I can see from the call stack that control is still with the unmanaged library. Unfortunately, this method doesn't offer a timeout. What I need to do is, within my managed code, cancel the call after a certain timeout period. I've tried a couple of approaches, including the following:</p>
  
  <pre><code>Task&lt;IWorkspace&gt; task = new Task&lt;IWorkspace&gt;(() =&gt; 
      { 
          return _workspaceFactory.OpenFromString(connectionString); 
      });
  if (!task.Wait(10000))
  {
      throw new TimeoutException();
  }
  IWorkspace workspace = task.Result;
  </code></pre>
  
  <p>In this case, <em>task.Wait()</em> always returns false, and <em>task.Result()</em> is always <code>null</code>, even if a valid value for <em>connectionString</em> is passed.</p>
  
  <p>I've also tried the following approach:</p>
  
  <pre><code>IWorkspace workspace = null;
  Thread thread = new Thread(() =&gt;
      {
          workspace = _workspaceFactory.OpenFromString(connectionString);
      });
  thread.Start();
  if (!thread.Join(10000))
  {
      throw new TimeoutException();
  }
  </code></pre>
  
  <p>In this case, if a valid value for <em>connectionString</em> is passed, execution works as expected, but if an invalid value is passed, the execution still hangs in the unmanaged code, and <em>thread.Join()</em> never returns.</p>
  
  <p>Any suggestions on how to do this?</p>