ASP.NET Web Form Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

ASP.NET Web Forms use async and await to perform asynchronous operations like database queries

Back to: ASP.NET Web Form Tutorial

In ASP.NET Web Forms, you can use async and await to perform asynchronous operations like database queries. This helps keep the UI responsive by avoiding the blocking of the main thread while waiting for the database operation to complete.

Here's how you can do it:

Example: Asynchronous Database Query in ASP.NET Web Forms

Code-Behind (C#)

c#
using System;
using System.Data.SqlClient;
using System.Threading.Tasks;
public partial class AsyncDemo : System.Web.UI.Page
{
protected async void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string result = await GetDatabaseDataAsync(); lblResult.Text = result;
}
}
private async Task GetDatabaseDataAsync()
{
string connectionString = "your_connection_string_here";
string query = "SELECT TOP 1 [ColumnName] FROM [YourTable]";
using (SqlConnection connection = new SqlConnection(connectionString))
{
await connection.OpenAsync();
// Open the connection asynchronously
using (SqlCommand command = new SqlCommand(query, connection))
{
object result = await command.ExecuteScalarAsync();
// Execute query asynchronously
return result?.ToString() ?? "No data found";
}
}
}
}

Explanation:

  1. Async Event Handler: The Page_Load method is marked async and calls an asynchronous method GetDatabaseDataAsync.
  2. Database Query: The GetDatabaseDataAsync method:
    • Uses OpenAsync to open the database connection asynchronously.
    • Uses ExecuteScalarAsync to fetch the query result asynchronously.
  3. UI Update: After the database operation completes, the result is displayed on the page by setting the Text property of lblResult.

Benefits:

  • Non-Blocking: The UI thread is free to handle other tasks while waiting for the database operation to complete.
  • Scalability: Frees up server resources, allowing the application to handle more concurrent requests efficiently.

Note:

  • Ensure that your database provider supports asynchronous operations. Most modern ADO.NET providers, including SQL Server, do.
  • Asynchronous programming in Web Forms is generally used for operations where the response time might be long, such as database queries or external API calls.
Scroll to Top