I switched this site’s analytics to
Fathom Analytics to protect
your privacy →
Get $10 OFF your first invoice.
Using SqlDataReader asynchronously prevents blocking the main thread, improving performance in web apps and large queries. Here’s how to do it properly.
Use await with ExecuteReaderAsync()
using (SqlConnection conn = new SqlConnection(connectionString))
{
await conn.OpenAsync();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users", conn))
using (SqlDataReader reader = await cmd.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
Console.WriteLine(reader["Username"]);
}
} // ✅ Auto-closes reader
} // ✅ Auto-closes connection
Why use async?
A couple of reasons:
- Frees up the thread while waiting for the database.
- Improves scalability in ASP.NET Core and web apps.
⚡ Alternative: ConfigureAwait(false) for ASP.NET
Use ConfigureAwait(false) in library code to avoid deadlocks in UI frameworks like ASP.NET.
using (SqlConnection conn = new SqlConnection(connectionString))
{
await conn.OpenAsync().ConfigureAwait(false);
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users", conn))
using (SqlDataReader reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false))
{
while (await reader.ReadAsync().ConfigureAwait(false))
{
Console.WriteLine(reader["Username"]);
}
}
}