title: How to stop thread reuse while still having uncompleted child-threads in ASP .NET Core request pipeline?
body: <p>I have a webapi with a custom execution context set on the request pipeline using a middleware something like this:</p>
  
  <pre><code>public async Task Invoke(HttpContext httpContext)
  {
    using (Context.With(new TokenContext("token")))
    {
      await _next(httpContext);
    }
  }
  </code></pre>
  
  <p>And the Context-manager looks a bit like this with a stack of <code>IContext</code> objects that are local to the current thread (and the threads it create).</p>
  
  <pre><code>public static class Context
  {
    private static AsyncLocal&lt;Stack&lt;IContext&gt;&gt; _current = new AsyncLocal&lt;Stack&lt;IContext&gt;&gt;();
    public static IContext Current
    {
      get
      {
        return _current.Value != null &amp;&amp; _current.Value.Count &gt; 0 ?_current.Value.Peek() : null;
      }
    }
  
    public static IDisposable With(IContext context)
    {
      Assert.IsNotNull(context);
  
      if (_current.Value == null) _current.Value = new Stack&lt;IContext&gt;();
      _current.Value.Push(context);
  
      return new DelegateDisposable(() =&gt;
      {
        _current.Value.Pop();
      });
    }
  }
  </code></pre>
  
  <p>The problem I experience is when having multiple requests going on at the same time. Sometimes I get issues with the current context not being what I expected. I have noticed that the current context sometimes have a value already before I set it with the using-statement. My conclusion is that the initial thread used for the request is returned to a thread pool when hitting the <code>await _next</code> line and that this thread is/can be reused for following requests, which sometimes happen before "child-threads" have completed. This leaves me with a lot of unpredictable behavior.</p>
  
  <p>So, my question: How can I tweak this so that I don't run into this issue? Can I force the request-pipeline to not return threads before all "child-threads" have completed? Will this be inefficient? Can I force the "mother-thread" to clean up it's reference to the context-stack before it returns itself to the pool?</p>
  
  <p>Any other options?</p>