title: Lazy shared async resource — Clarification?
body: <p>I saw this example at the end of Stephen's book.</p>
  
  <p>This code can be accessed by <em>more</em> than one thread.</p>
  
  <pre><code>static int _simpleValue;
  static readonly Lazy&lt;Task&lt;int&gt;&gt; MySharedAsyncInteger = new Lazy&lt;Task&lt;int&gt;&gt;(  
  async () =&gt;
  {
     await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
     return _simpleValue++;
  });
  
  async Task GetSharedIntegerAsync()
  {
      int sharedValue = await MySharedAsyncInteger.Value;
  }
  </code></pre>
  
  <p>No matter how many parts of the code call Value simultaneously, the
  <code>Task&lt;int&gt;</code> is only created <em>once</em> and returned to all callers.</p>
  
  <p>But then he says : </p>
  
  <blockquote>
    <p>If there are different thread types that may call <code>Value</code> (e.g., a UI
    thread and a thread-pool thread, or two different ASP.NET request
    threads), then it may be better to always execute the asynchronous
    delegate on a thread-pool thread.</p>
  </blockquote>
  
  <p>So he suggests the following code which makes the whole code run in a threadpool thread : </p>
  
  <pre><code>static readonly Lazy&lt;Task&lt;int&gt;&gt; MySharedAsyncInteger = new Lazy&lt;Task&lt;int&gt;&gt;(() =&gt; Task.Run(
  async () =&gt;
  {
      await Task.Delay(TimeSpan.FromSeconds(2));
      return _simpleValue++;;
  }));
  </code></pre>
  
  <p><strong>Question:</strong></p>
  
  <p>I don't understand what's the problem with the <em>first</em> code. The continuation  would be executed in a threadpool thread (due to ConfigureAwait ,  we don't need the original context).</p>
  
  <p>Also as soon that any control from any thread will reach the <code>await</code> , the control will be back to the caller.</p>
  
  <p>I don't see what  <em>extra</em> risk the second code is trying to resolve.</p>
  
  <p>I mean - what is the problem with "<em>different thread types that may call <code>Value</code></em>" in the <em>first</em> code?</p>