title: Is it possible to detect if you are on the synchronous side of an async method?
body: <p>I am trying to develop a context system for a web application which will propagate data along the logical flow of control. This is similar to AsyncLocal stack described <a href="http://blog.stephencleary.com/2013/04/implicit-async-context-asynclocal.html" rel="nofollow">enter link description here</a>.</p>
  
  <p>Originally, I was simply using the LogicalCallContext to do this, but this runs into issues with ASP.NET thread agility. To counter this, I have implemented a hybrid system that uses both the logical call context and HttpContext.Items. With this system, we keep the two contexts in sync (assuming both are available), and trust the logical call context unless it is missing and there is something in HttpContext.Items.</p>
  
  <p>This works in almost all cases, but can run into trouble in the first half of an async method that is called from a synchronous method where we are on the request thread but in a different logical call context. Here's an example:</p>
  
  <pre><code>// in BeginRequest
  MyContext.Push("BeginRequest");
  
  public ActionResult SomeAction() 
  {
      // sometimes Asp.NET does a thread switch between begin request and the action
      // in that case, we have:
      // Logical: null
      // HttpContext:  "BeginRequest"
  
      var result = this.DoSomethingAsync().Result;
  
      // Here we have
      // Logical: null
      // THIS IS WRONG: the logical context was correctly restored by async magic, but we
      // corrupted the HttpContext. Since we lost the logical call context, we can't use that
      // HttpContext: "DoSomethingAsync" -&gt; "BeginRequest"
  }
  
  private async Task DoSomethingAsync()
  {
      // right now we're on the request thread, so we still have HttpContext but
      // because we have a logical call context 
      // I would like to detect when the code is in THIS STATE
      MyContext.Push("DoSomethingAsync");
  
      // Here we have
      // Logical: "DoSomethingAsync" -&gt; "BeginRequest"
      // HttpContext: "DoSomethingAsync" -&gt; "BeginRequest"
  
      // because this method does ConfigureAwait(false), on the other side of await
      // you won't have the context
      await ComputeSomethingAsync().ConfigureAwait(false);
  
      // Here we have
      // Logical: "DoSomethingAsync" -&gt; "BeginRequest"
      // HttpContext: null    
  
      MyContext.Pop();
  
      // Here we have
      // Logical: "BeginRequest"
      // HttpContext: null    
  }
  </code></pre>
  
  <p>Is there any way to detect this state? Is there another way to get a consistent logical context flow in ASP.NET/.NET 4.5?</p>