How do you perform asynchronous database operations in ADO.NET?
ADO.NET supports asynchronous database operations using the async and await
keywords in C#. This allows the application to remain responsive while waiting for the
database operation to complete.
- ExecuteNonQueryAsync: Executes a SQL command asynchronously.
- ExecuteReaderAsync: Executes a query and returns a SqlDataReader
asynchronously.
- ExecuteScalarAsync: Executes a query and returns a single value asynchronously.
Example:
public async Task GetDataAsync()
SqlConnection connection = new SqlConnection(connectionString);
await connection.OpenAsync();
SqlCommand command = new SqlCommand("SELECT * FROM Customers",
connection);
SqlDataReader reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
Console.WriteLine(reader["CustomerName"].ToString());
reader.Close();
Follow: