title: Why can't I use the 'await' operator within the body of a lock statement?
body: <p>The await keyword in C# (.NET Async CTP) is not allowed from within a lock statement.</p>
  
  <p>From <a href="http://msdn.microsoft.com/en-us/library/hh191443%28v=vs.110%29.aspx">MSDN</a>:</p>
  
  <blockquote>
    <p><strong>An
    await expression cannot be used</strong> in a synchronous function, in a query
    expression, in the catch or finally block of an exception handling
    statement, <strong>in the block of a lock statement</strong>, or in an unsafe context.</p>
  </blockquote>
  
  <p>I assume this is either difficult or impossible for the compiler team to implement for some reason.</p>
  
  <p>I attempted a work around with the using statement:</p>
  
  <pre><code>class Async
  {
      public static async Task&lt;IDisposable&gt; Lock(object obj)
      {
          while (!Monitor.TryEnter(obj))
              await TaskEx.Yield();
  
          return new ExitDisposable(obj);
      }
  
      private class ExitDisposable : IDisposable
      {
          private readonly object obj;
          public ExitDisposable(object obj) { this.obj = obj; }
          public void Dispose() { Monitor.Exit(this.obj); }
      }
  }
  
  // example usage
  using (await Async.Lock(padlock))
  {
      await SomethingAsync();
  }
  </code></pre>
  
  <p>However this does not work as expected.  The call to Monitor.Exit within ExitDisposable.Dispose seems to block indefinitely (most of the time) causing deadlocks as other threads attempt to acquire the lock.  I suspect the unreliability of my work around and the reason await statements are not allowed in lock statement are somehow related.</p>
  
  <p>Does anyone know <em>why</em> await isn't allowed within the body of a lock statement?</p>