C#  

Asynchronous Programming in C#: async and await

Concept Overview

In ASP.NET WebForms, if you perform heavy operations (like calling an API, reading large files, or querying databases) in the normal synchronous way, the web page freezes until the task completes.

To avoid blocking the main thread, we use async and await keywords to run long operations asynchronously, so the web server can handle other requests in parallel.

Real-Time Example Scenario

Imagine you have a web page that fetches weather data from an API or simulates a slow background process (e.g., generating a report).
Instead of freezing the page, you want it to respond quickly while the background task completes asynchronously.

ASP.NET WebForms Example

File: AsyncDemo.aspx

<%@ Page Language="C#" Async="true" AutoEventWireup="true" CodeBehind="AsyncDemo.aspx.cs" Inherits="WebApp.AsyncDemo" %>

<!DOCTYPE html>
<html>
<head>
    <title>Asynchronous Programming in ASP.NET WebForms</title>
</head>
<body>
    <form id="form1" runat="server">
        <h2>Asynchronous Programming Example - async / await</h2>

        <asp:Button ID="btnProcess" runat="server" Text="Start Long Operation" OnClick="btnProcess_Click" />
        <br /><br />

        <asp:Label ID="lblStatus" runat="server" Text="Click the button to start..."></asp:Label>
    </form>
</body>
</html>

File: AsyncDemo.aspx.cs

using System;
using System.Threading.Tasks;

namespace WebApp
{
    public partial class AsyncDemo : System.Web.UI.Page
    {
        // Button click handler marked as async
        protected async void btnProcess_Click(object sender, EventArgs e)
        {
            lblStatus.Text = "Processing started... Please wait.";

            // Run a long-running task asynchronously
            string result = await GenerateReportAsync();

            // Update label after task completes
            lblStatus.Text = result;
        }

        // Simulating a long-running background task
        private async Task<string> GenerateReportAsync()
        {
            // Simulate a 5-second background operation
            await Task.Delay(5000);

            // After the delay, return result
            return "Report generated successfully at " + DateTime.Now.ToLongTimeString();
        }
    }
}

Output

When you click “Start Long Operation”:

  1. The label immediately shows “Processing started… Please wait.”

  2. The page doesn’t freeze — server continues handling other requests.

  3. After ~5 seconds, the label updates to:

    “Report generated successfully at 12:34:56 PM”

Real-Time Use Case Examples

ScenarioDescription
Fetching API DataCall external REST APIs (e.g., weather, payment, stock data) asynchronously
File Upload/DownloadHandle large file operations without blocking user
Database QueriesFetch data from SQL asynchronously to improve scalability
Email SendingSend confirmation emails without making the user wait
Background ReportsGenerate PDF/Excel reports asynchronously and notify later

Key Points

  • Use Async="true" in the page directive for async event handlers.

  • The method signature should include async and return Task or Task<T>.

  • Use await before the long-running task.

  • The server can handle multiple requests while one is awaiting.

Example Enhancement

You can extend this example to:

  • Display a progress bar or spinner during async operation.

  • Call an API (HttpClient) asynchronously instead of Task.Delay.

  • Save the result to a database or file once completed.