title: Should I call ConfigureAwait(false) on every awaited operation
body: <p>I read this article <a href="https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html" rel="noreferrer">https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html</a> - however I'm seeing a contradiction:</p>
  
  <p>I'm aware of the problem of deadlocking the UI thread because the UI thread blocks waiting for an async operation to complete, but the same async operation is synchronized to the UI thread context - consequently the async operation cannot enter the UI thread, so the UI thread won't stop waiting.</p>
  
  <p>The article tells us the workaround is to not block on the UI thread, otherwise you need to use <code>ConfigureAwait(false)</code> <strong>everywhere</strong>:</p>
  
  <blockquote>
    <p>You would have to use  for every await in the transitive closure of all methods called by the blocking code, including all third- and second-party code.</p>
  </blockquote>
  
  <p>However later on in the article the author writes:</p>
  
  <blockquote>
    <p>Preventing the Deadlock<br>
    There are two best practices (both covered in my intro post) that avoid this situation:  </p>
    
    <ol>
    <li>In your “library” async methods, use <code>ConfigureAwait(false)</code> wherever possible.  </li>
    <li>Don’t block on Tasks; use <code>async</code> all the way down.</li>
    </ol>
  </blockquote>
  
  <p>I'm seeing a contradiction here - in the "don't do this" section he writes that having to use <code>ConfigureAwait(false)</code> everywhere would be the consequence of blocking the UI thread - but in his "best practices" list he then tells us to do just that: "use <code>ConfigureAwait(false)</code> wherever possible." - though I suppose "wherever possible" would exclude third-party code, but in the case where there is no third-party code the result is the same if I block the UI thread or not.</p>
  
  <p>As for my specific problem, here is my current code in a WPF MVVM project:</p>
  
  <h3>MainWindowViewModel.cs</h3>
  
  <pre><code>private async void ButtonClickEventHandler()
  {
      WebServiceResponse response = await this.client.PushDinglebopThroughGrumbo();
  
      this.DisplayResponseInUI( response );
  }
  </code></pre>
  
  <h3>WebServiceClient.cs</h3>
  
  <pre><code>public class PlumbusWebServiceClient {
  
      private static readonly HttpClient _client = new HttpClient();
  
      public async Task&lt;WebServiceResponse&gt; PushDinglebopThroughGrumbo()
      {
          try
          {
              using( HttpResponseMessage response = await _client.GetAsync( ... ) )
              {
                  if( !response.IsSuccessStatusCode ) return WebServiceResponse.FromStatusCode( response.StatusCode );
  
                  using( Stream versionsFileStream = await response.Content.ReadAsStreamAsync() )
                  using( StreamReader rdr = new StreamReader( versionsFileStream ) )
                  {
                      return await WebServiceResponse.FromResponse( rdr );
                  }
              }
          }
          catch( HttpResponseException ex )
          {
              return WebServiceResponse.FromException( ex );
          }
      }
  }
  </code></pre>
  
  <p>If I understand the document correctly, I should add <code>ConfigureAwait(false)</code> to <em>every</em> <code>await</code> that is not in a method that has code that needs to run on the UI thread - which is every method inside my <code>PushDinglebopThroughGrumbo</code> method, but also all code in <code>WebServiceResponse.FromResponse</code> (which calls <code>await StreamReader.ReadLineAsync</code>). But what about any third-party code I call which also performs <code>await</code> operations on the <code>StreamReader</code>? I won't have access to their source-code so that would be impossible.</p>
  
  <p>I'm also a bit put-off by having to place <code>ConfigureAwait(false)</code> everywhere - I thought the point of the <code>await</code> keyword was to eliminate explicit task library calls - shouldn't there be a different keyword for resume-context-free awaiting then? (e.g. <code>awaitfree</code>).</p>
  
  <p>So should my code then look like this?</p>
  
  <h3>MainWindowViewModel.cs</h3>
  
  <pre><code>(unmodified, same as above)
  </code></pre>
  
  <h3>WebServiceClient.cs</h3>
  
  <pre><code>public class PlumbusWebServiceClient {
  
      private static readonly HttpClient _client = new HttpClient();
  
      public async Task&lt;WebServiceResponse&gt; PushDinglebopThroughGrumbo()
      {
          try
          {
              using( HttpResponseMessage response = await _client.GetAsync( ... ).ConfigureAwait(false) ) // &lt;-- here
              {
                  if( !response.IsSuccessStatusCode ) return WebServiceResponse.FromStatusCode( response.StatusCode );
  
                  using( Stream versionsFileStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false) )  // &lt;-- and here
                  using( StreamReader rdr = new StreamReader( versionsFileStream ) )
                  {
                      return await WebServiceResponse.FromResponse( rdr ).ConfigureAwait(false);  // &lt;-- and here again, and inside `FromResponse` too
                  }
              }
          }
          catch( HttpResponseException ex )
          {
              return WebServiceResponse.FromException( ex );
          }
      }
  }
  </code></pre>
  
  <p>...I would have thought that calling <code>ConfigureAwait(false)</code> would only be necessary on the topmost <code>await</code> call inside the <code>PlumbusWebServiceClient</code> method - i.e. the <code>GetAsync</code> call.</p>
  
  <p>If I do need to apply it everywhere, could I simplify it to an extension method?</p>
  
  <pre><code>public static ConfiguredTaskAwaitable&lt;T&gt; CF&lt;T&gt;(this Task&lt;T&gt; task) {
      return task.ConfigureAwait(false);
  }
  
  using( HttpResponseMessage response = await _client.GetAsync( ... ).CF() )
  {
      ...
  }
  </code></pre>
  
  <p>...though this doesn't alleviate all of the fiddliness.</p>
  
  <h3>Update: Second example</h3>
  
  <p>Here is some async code I wrote that exports my application's settings to a simple text file - I can't help but think it doesn't feel right, is this really the correct way to do this?</p>
  
  <pre><code>class Settings
  {
      public async Task Export(String fileName)
      {
          using( StreamWriter wtr = new StreamWriter( fileName, append: false ) )
          {
              await ExportSetting( wtr, nameof(this.DefaultStatus     ), this.DefaultStatus                         ).ConfigureAwait(false);
              await ExportSetting( wtr, nameof(this.ConnectionString  ), this.ConnectionString                      ).ConfigureAwait(false);
              await ExportSetting( wtr, nameof(this.TargetSystem      ), this.TargetSystem.ToString("G")            ).ConfigureAwait(false);
              await ExportSetting( wtr, nameof(this.ThemeBase         ), this.ThemeBase                             ).ConfigureAwait(false);
              await ExportSetting( wtr, nameof(this.ThemeAccent       ), this.ThemeAccent                           ).ConfigureAwait(false);
              await ExportSetting( wtr, nameof(this.ShowSettingsButton), this.ShowSettingsButton ? "true" : "false" ).ConfigureAwait(false);
              await ExportSetting( wtr, nameof(this.ShowActionsColumn ), this.ShowActionsColumn  ? "true" : "false" ).ConfigureAwait(false);
              await ExportSetting( wtr, nameof(this.LastNameFirst     ), this.LastNameFirst      ? "true" : "false" ).ConfigureAwait(false);
              await ExportSetting( wtr, nameof(this.TitleCaseCustomers), this.TitleCaseCustomers ? "true" : "false" ).ConfigureAwait(false);
              await ExportSetting( wtr, nameof(this.TitleCaseVehicles ), this.TitleCaseVehicles  ? "true" : "false" ).ConfigureAwait(false);
              await ExportSetting( wtr, nameof(this.CheckForUpdates   ), this.CheckForUpdates    ? "true" : "false" ).ConfigureAwait(false);
          }
      }
  
      private static async Task ExportSetting(TextWriter wtr, String name, String value)
      {
          String valueEnc = Uri.EscapeDataString( value ); // to encode line-breaks, etc.
  
          await wtr.WriteAsync( name ).ConfigureAwait(false);
          await wtr.WriteAsync( '=' ).ConfigureAwait(false);
          await wtr.WriteLineAsync( valueEnc ).ConfigureAwait(false);
      }
  }
  </code></pre>