LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
C# Programming

Async and Await in C# – Asynchronous Programming

Async and await help applications perform operations without blocking the current thread while waiting for work to finish. A thread is a path of execution in a program. This is especially useful for database calls, API requests and file operations. It helps applications remain responsive while waiting for external operations.

1Why Do We Need Async and Await?

Hi friends! In this article, we will learn async and await in C#. These keywords help us execute time-consuming operations without blocking the calling thread. For example, when an application calls an API, reads a file or queries a database, it can continue handling other work while waiting for the result. This makes applications more responsive and improves scalability, especially in ASP.NET Core Web APIs.

RememberAsynchronous programming means starting an operation and continuing other work without waiting synchronously for it to finish.

2Think About Booking a Train Ticket

Imagine booking a train ticket using an application. After clicking Book, the application sends a request to the railway server.

While the server checks seat availability and processes payment, you don't want the entire application to freeze. You can continue interacting with the application.

Similarly, C# uses async and await to wait for operations such as database calls and HTTP requests without blocking the current thread.

3Understand These Important Keywords

1. async

The async keyword marks a method as asynchronous. It allows us to use await inside that method.

2. await

The await keyword waits for an asynchronous operation to complete. It does not block the thread while the operation is waiting.

3. Task

Task represents an asynchronous operation that may complete in the future. Task<T> represents an operation that returns a value of type T.

4. Task.Delay()

Task.Delay() asynchronously waits for a specified duration. We use it here to simulate a time-consuming operation.

Method return type Purpose
void No return value (generally avoid for async methods).
Task Async operation without a result.
Task<T> Async operation returning a value.
Pro TipPrefer Task or Task<T> for asynchronous methods. Use async void mainly for event handlers.

4Let's Build an Async C# Program

Let's create a console application that checks an order status. The application waits for the simulated server response and then displays the result.

Program.cs
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.WriteLine("Checking order...");

        string status =
            await GetOrderStatusAsync();

        Console.WriteLine($"Order status: {status}");
        Console.WriteLine("Thank you!");
    }

    static async Task<string>
        GetOrderStatusAsync()
    {
        await Task.Delay(2000);
        return "Shipped";
    }
}

Here, Main is asynchronous. It calls GetOrderStatusAsync(), which waits for two seconds using Task.Delay(). After completion, it returns the order status.

Common MistakeCalling .Result or .Wait() can block threads and may cause deadlocks in certain synchronization contexts. Prefer await.

5What Will the Console Display?

The first message appears immediately. After the asynchronous operation completes, the remaining messages are displayed.

Output
Checking order...
Order status: Shipped
Thank you!

The order status appears only after the awaited operation completes.

6Watch Async Code Run in VS Code

Follow how the program executes, waits for the asynchronous operation and displays the final result.

● Program.cs - Visual Studio Code
◫
⌕
⑂
▣
● Program.cs
 
PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL
 
Ln 1, Col 1 UTF-8   C#
Preparing the program...

7Let's Revise What We Learned

Async and await help us write responsive applications. They are especially useful when working with databases, external APIs and file operations.

Remember these three key takeaways:

  • async: Marks a method as asynchronous.
  • await: Asynchronously waits for an operation to finish.
  • Task: Represents an asynchronous operation.

8Questions Interviewers Love to Ask

Q1Easy

What is async and await in C#?

Answer
They are keywords used for asynchronous programming. They help applications wait for operations without blocking the current thread.

Q2Easy

What is the difference between Task and Task<T>?

Answer
Task represents an asynchronous operation without a result. Task<T> represents an operation that returns a value.

Q3Medium

Does await create a new thread?

Answer
No. Await does not automatically create a new thread. It allows the current method to suspend while the asynchronous operation completes.

Q4Medium

Can we use await without async?

Answer
In traditional async methods, await must be inside an async method or lambda. Modern C# also supports top-level await in suitable contexts.

Q5Medium

What is the difference between synchronous and asynchronous programming?

Answer
Synchronous execution waits for an operation to finish before continuing. Asynchronous execution allows other work to continue while an operation is waiting.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.