title: Executing a stored procedure asynchronously without awaiting it and blocking the UI
body: <p>I have several stored procedures that INSERT or UPDATE into the database in my ASP.NET web forms application. I want these queries to execute, but I don't want the user's UI or page execution to await them finishing. They don't take very long (much less than a second), but that's a second that the user has to wait for the page load.</p>
  
  <p>I'm typically looking at inserting logging or history into a table. The user's page view isn't dependent on the execution or results of the query.</p>
  
  <p>I'm trying to use .NET's async methods, like ExecuteNonQueryAsync(). But I think I've got this wrong conceptually. ExecuteNonQueryAsync() seems to be for running two or more longer-running database operations in parallel, and blocking the UI until both are complete.</p>
  
  <pre><code>private async Task&lt;string&gt; DoTransaction()
  {
      string value = "";
  
      using (SqlConnection objCS = DB.AdminNET())
      {
          await objCS.OpenAsync();
          using (SqlTransaction t = objCS.BeginTransaction())
          using (SqlCommand objCommand = new SqlCommand("WAITFOR DELAY '00:00:05'; EXEC logtiming @line", objCS, t))
          {
              try
              {
                  objCommand.Parameters.Add("@line", SqlDbType.VarChar).Value = "log me";
                  await objCommand.ExecuteNonQueryAsync();
              }
              catch
              {
                  t.Rollback();
                  throw;
              }
  
              t.Commit();
  
              value = "done";
          }
      }
  
      return value;
  }
  
  protected async void Page_Load(object sender, EventArgs e)
  {
      await DoTransaction(g);
  }
  </code></pre>
  
  <p>This code will insert my test data after the introduced delay. However, it holds the whole page response to the user until the delay is over. Ideally, I would want the page to return to the user immediately and then five seconds later I'd see my results in the table. Is ExecuteNonQueryAsync() the wrong tool for this? Or is there some change I can make that I haven't found yet, eg. "not await"?</p>