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())
{
.....