title: How to check that AsyncLocal<T> is accessed within same "async context"
body: <p><strong>TL;DR</strong> <code>ThreadLocal&lt;T&gt;.Value</code> points to same location if <code>Thread.CurrentThread</code> stays the same. Is there anything similar  for <code>AsyncLocal&lt;T&gt;.Value</code> (e.g. would <code>SychronizationContext.Current</code> or <code>ExecutionContext.Capture()</code> suffice for all scenarios)?</p>
  
  <hr>
  
  <p>Imagine we have created some snapshot of data structure which is kept in thread-local storage (e.g. <code>ThreadLocal&lt;T&gt;</code> instance) and passed it to axillary class for later use. This axillary class is used to restore this data structure to snapshot state. We don't want to restore this snapshot onto different thread, so we can check on which thread axillary class was created. For example: </p>
  
  <pre><code>class Storage&lt;T&gt;
  {
      private ThreadLocal&lt;ImmutableStack&lt;T&gt;&gt; stackHolder;
  
      public IDisposable Push(T item)
      {
          var bookmark = new StorageBookmark&lt;T&gt;(this);
          stackHolder.Value = stackHolder.Value.Push(item);
          return bookmark;
      }
  
      private class StorageBookmark&lt;TInner&gt; :IDisposable
      {
          private Storage&lt;TInner&gt; owner;
          private ImmutableStack&lt;TInner&gt; snapshot;
          private Thread boundThread;
  
          public StorageBookmark(Storage&lt;TInner&gt; owner)
          { 
               this.owner = owner;
               this.snapshot = owner.stackHolder.Value;
               this.boundThread  = Thread.CurrentThread;
          }
  
          public void Dispose()
          {
               if(Thread.CurrentThread != boundThread) 
                   throw new InvalidOperationException ("Bookmark crossed thread boundary");
               owner.stackHolder.Value = snapshot;
          }
      }
  }
  </code></pre>
  
  <p>With this, we essentialy bound StorageBookmark to specific thread, and, therefore, to specific version of data structure in ThreadLocal storage. And we did that by assuring we don't cross "thread context" with the help of <code>Thread.CurrentThread</code> <br/><br/>
  Now, to question at hand. How can we achieve the same behavior with <code>AsyncLocal&lt;T&gt;</code> instead of <code>ThreadLocal&lt;T&gt;</code>? To be precise, is there anything similar to <code>Thread.CurrentThread</code> which can be checked at times of construction and usage to control that "async context" has not been crossed (That means <code>AsyncLocal&lt;T&gt;.Value</code> would point to same object as when bookmark was constructed).<br/>
  It seems either <code>SynchronizationContext.Current</code> or <code>ExecutionContext.Capture()</code> may suffice, but I'm not sure which is better and that there is no catch (or even that would work in all possible situations)</p>