title: Better time-out detection for synchronous operations
body: <p>I need a way to perform some action synchronously which should complete in half a second, but might just hang around for minutes. If it times out I don't care about the result. Here's the I'm doing it right now using compiler-generated delegate.BeginInvoke:</p>
  
  <pre><code>static void Main()
  {
      bool disposed = false;
      var wait = new ManualResetEvent(false);
      var a = new Action(
          () =&gt;
              {
                  Thread.Sleep(1000); // &lt;- some looong action
  
                  if (!disposed)
                      lock (wait)
                          if (!disposed)
                              wait.Set();
              });
  
      a.BeginInvoke(a.EndInvoke, null);
  
      bool success = wait.WaitOne(500);
      Console.WriteLine(success ? "success" : "timeout");
  
      lock (wait)
      {
          wait.Dispose();
          disposed = true;
      }
  
      Console.ReadLine();
  }
  </code></pre>
  
  <p>Looks ugly. And I'm aware lambda closure's <code>disposed</code> variable is modified (unlike my ReSharper, I like this C# feature). All because I want to dispose <code>ManualResetEvent</code>. Can you suggest better approach in .NET4? Perhaps should I just skip disposing the event and rely on GC?</p>
  
  <p>One note: <code>ManualResetEvent.Set()</code> explodes if you try to do it on disposed instance.</p>