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";
}
}
}
}
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
{
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:
- Async Event Handler: The
Page_Load
method is markedasync
and calls an asynchronous methodGetDatabaseDataAsync
. - Database Query: The
GetDatabaseDataAsync
method:- Uses
OpenAsync
to open the database connection asynchronously. - Uses
ExecuteScalarAsync
to fetch the query result asynchronously.
- Uses
- UI Update: After the database operation completes, the result is displayed on the page by setting the
Text
property oflblResult
.
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.