title: How do I make SqlDataReader.ReadAsync() run asynchronously?
body: <p>When making calls to SQL Server that actually do things that take time, <code>SqlDataReader.ReadAsync()</code> runs synchronously for me. Is there any way to force it to run asynchronously or is my only option to call it in <code>Task.Run()</code>?</p>
  
  <p>Here is a repro. It uses winforms to demonstrate that the call blocks the GUI thread. Note that the T-SQL has to actually do something—<strong>this is not reproducible with <code>WAITFOR DELAY '00:00:20'</code></strong>.</p>
  
  <pre><code>using System;
  using System.Configuration;
  using System.Data.Common;
  using System.Data.SqlClient;
  using System.Threading.Tasks;
  using System.Windows.Forms;
  
  static class SqlDataReaderReadAsyncProgram
  {
      static async void Form_Shown(object sender, EventArgs e)
      {
          var form = (Form)sender;
          // Declare your connection string in app.config like
          // &lt;connectionStrings&gt;&lt;remove name="LocalSqlServer"/&gt;&lt;add name="LocalSqlServer" connectionString="Data Source=localhost\SQLEXPRESS;Integrated Security=true"/&gt;&lt;/connectionStrings&gt;
          using (DbConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString))
          {
              form.Text = "connecting…";
              await connection.OpenAsync();
              form.Text = "connected!";
              // Install a stored procedure.
              using (var command = connection.CreateCommand())
              {
                  command.CommandText = "SET NOCOUNT ON"
                      + " SELECT 'a'"
                      + " DECLARE @t DATETIME = SYSDATETIME()"
                      + " WHILE DATEDIFF(s, @t, SYSDATETIME()) &lt; 20 BEGIN"
                      + "   SELECT 2 x INTO #y"
                      + "   DROP TABLE #y"
                      + " END"
                      + " SELECT 'b'";
                  form.Text = "executing…";
                  using (var reader = await command.ExecuteReaderAsync())
                  {
                      form.Text = "reading…";
                      do
                      {
                          // Blocks on the second call until the second resultset is returned by SQL Server
                          while (await reader.ReadAsync())
                          {
                          }
                      } while (await reader.NextResultAsync());
                      form.Text = "done!";
                  }
              }
          }
          await Task.Delay(TimeSpan.FromSeconds(5));
          form.Close();
      }
  
      [STAThread]
      static void Main()
      {
          Application.EnableVisualStyles();
          Application.SetCompatibleTextRenderingDefault(false);
          var form = new Form();
          form.Shown += Form_Shown;
          Application.Run(form);
      }
  }
  </code></pre>
  
  <p>When I run this, the window becomes “(Not Responding)” for 20 seconds before reporting it is done (note that when debugging in VS, “(Not Responding)” text does not appear but it still freezes the same). If I debug in VS and break it while it’s frozen, I see it sitting with a call stack that looks like this:</p>
  
  <pre><code>    [Managed to Native Transition]  
      System.Data.dll!SNINativeMethodWrapper.SNIReadSyncOverAsync(System.Runtime.InteropServices.SafeHandle pConn, ref System.IntPtr packet, int timeout) Unknown
      System.Data.dll!System.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync()   Unknown
      System.Data.dll!System.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket()   Unknown
      System.Data.dll!System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer()   Unknown
      System.Data.dll!System.Data.SqlClient.TdsParserStateObject.TryReadByteArray(byte[] buff, int offset, int len, out int totalRead)    Unknown
      System.Data.dll!System.Data.SqlClient.TdsParserStateObject.TryReadInt64(out long value) Unknown
      System.Data.dll!System.Data.SqlClient.TdsParser.TryProcessDone(System.Data.SqlClient.SqlCommand cmd, System.Data.SqlClient.SqlDataReader reader, ref System.Data.SqlClient.RunBehavior run, System.Data.SqlClient.TdsParserStateObject stateObj)    Unknown
      System.Data.dll!System.Data.SqlClient.TdsParser.TryRun(System.Data.SqlClient.RunBehavior runBehavior, System.Data.SqlClient.SqlCommand cmdHandler, System.Data.SqlClient.SqlDataReader dataStream, System.Data.SqlClient.BulkCopySimpleResultSet bulkCopyHandler, System.Data.SqlClient.TdsParserStateObject stateObj, out bool dataReady)  Unknown
      System.Data.dll!System.Data.SqlClient.SqlDataReader.TryHasMoreRows(out bool moreRows)   Unknown
      System.Data.dll!System.Data.SqlClient.SqlDataReader.TryReadInternal(bool setTimeout, out bool more) Unknown
      System.Data.dll!System.Data.SqlClient.SqlDataReader.ReadAsync.AnonymousMethod__0(System.Threading.Tasks.Task t) Unknown
      System.Data.dll!System.Data.SqlClient.SqlDataReader.InvokeRetryable&lt;bool&gt;(System.Func&lt;System.Threading.Tasks.Task, System.Threading.Tasks.Task&lt;bool&gt;&gt; moreFunc, System.Threading.Tasks.TaskCompletionSource&lt;bool&gt; source, System.IDisposable objectToDispose)   Unknown
      System.Data.dll!System.Data.SqlClient.SqlDataReader.ReadAsync(System.Threading.CancellationToken cancellationToken) Unknown
      System.Data.dll!System.Data.Common.DbDataReader.ReadAsync() Unknown
  &gt;   SqlDataReaderReadAsync.exe!SqlDataReaderReadAsyncProgram.Form_Shown(object sender, System.EventArgs e) Line 36  C#
      [Resuming Async Method] 
  </code></pre>
  
  <p>(further trimmed for brevity).</p>
  
  <p>The whole <code>ReadSyncOverAsync</code> stuff looks particularly suspicious to me. It’s like the SqlClient is assuming a synchronous read will not block, as if it doesn’t know how to use non-blocking IO or something. Yet when viewing reference source or decompiling with JustDecompile, it looks like there’s supposed to be async support but it just somehow heuristically/fallbackedly decided not to use it.</p>
  
  <p>So, how do I get the *<code>Async()</code> stuff in SqlClient to actually be async? I thought that these methods were supposed to enable me to write thread-free responsive GUI programs without needing to use <code>Task.Run()</code> because wrapping synchronous things in <code>Task.Run()</code> just to make them asynchronous is pointless overhead…?</p>
  
  <p>I’m using .net-4.7.02542.</p>
  
  <p>I’m assuming this is a .net bug and have submitted <a href="https://connect.microsoft.com/VisualStudio/feedback/details/3139210" rel="nofollow noreferrer">connect #3139210</a> (EDIT: connect is dead, I have a repro project at <a href="https://github.com/binki/connect3139210" rel="nofollow noreferrer">https://github.com/binki/connect3139210</a>).</p>
  
  <p><strong>UPDATE</strong>: Microsoft acknowledges the bug and will fix it in .net-4.7.3. <em>I used a “Technical Support” case from a VS subscription to report the bug and get this information.</em></p>