简体   繁体   中英

Why await for async method in the middle of a method?

I found this example using async/await stuff in a book. Could please someone tell me what's the benefit of awaiting for async methods like in the example below?

using (SqlConnection connection = new SqlConnection(connectionString))
{
  SqlCommand command = new SqlCommand("SELECT * FROM People", connection);
  await connection.OpenAsync();
  SqlDataReader dataReader = **await** command.ExecuteReaderAsync();
  while (**await** dataReader.ReadAsync())
  {
    string formatStringWithMiddleName = "Person ({0}) is named {1} {2} {3}";
    string formatStringWithoutMiddleName = "Person ({0}) is named {1} {3}";
    if ((dataReader["middlename"] == null))
    {
      Console.WriteLine(formatStringWithoutMiddleName,
      dataReader["id"],
      dataReader["firstname"],
      dataReader["lastname"]);
    }
    else
    {
      Console.WriteLine(formatStringWithMiddleName,
      dataReader["id"],
      dataReader["firstname"],
      dataReader["middlename"],
      dataReader["lastname"]);
    }
  }
  dataReader.Close();
  }
}

I just can't wrap my head around this. The way I understand, await blocks until the method called (in this case, ExecuteReaderAsync and ReadAsync) returns. What's the point of calling an async method and blocking right away in the middle of the code, without actually doing anything between the call to the async method and the point when the result is returned to the caller? How is it faster or more efficient than simply doing this?

....

SqlDataReader dataReader = command.ExecuteReader();
      while (dataReader.Read())
      {
           .....

The way I understand, await blocks until the method called (in this case, ExecuteReaderAsync and ReadAsync) returns.

No; await will pause the method and return to the caller. Thus, it does not block the calling thread for the duration of the ReadAsync operation.

Conceptually, it's the difference between synchronous and serial . Synchronous means blocking: the method call stops the thread until the Read completes. Serial means one at a time: the method will pause execution until the ReadAsync completes. So, the common await *Async() pattern is serial, but in an asynchronous way, not a synchronous way.

For more information about async and await , see my async intro post.

This temporarily blocks your method but keeps the UI-thread responding. Internally C# rewrites the method. The part after await is converted to a kind callback method (well not really, but you can imagine it was). The method returns immediately at the await and resumes where it has left off, when the async operation finishes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM