0
0
CsharpHow-ToBeginner · 4 min read

How to Use Async Await in C#: Simple Guide

In C#, use async to mark a method as asynchronous and await to pause execution until a task completes without blocking the thread. This lets your program run other work while waiting for long tasks like file reading or web requests.
📐

Syntax

The async keyword is added before the method return type to declare it as asynchronous. Inside this method, use await before a call to a method that returns a Task or Task<T>. This pauses the method until the awaited task finishes, then resumes with the result.

  • async: marks the method as asynchronous
  • await: waits for the task to complete without blocking
  • Task: represents an ongoing operation
  • Task<T>: represents an ongoing operation that returns a value
csharp
public async Task<int> GetNumberAsync()
{
    await Task.Delay(1000); // wait 1 second asynchronously
    return 42;
}
💻

Example

This example shows an asynchronous method that waits 2 seconds and then returns a message. The Main method calls it with await and prints the result. The program does not freeze while waiting.

csharp
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string message = await GetMessageAsync();
        Console.WriteLine(message);
    }

    static async Task<string> GetMessageAsync()
    {
        await Task.Delay(2000); // simulate work
        return "Hello after 2 seconds!";
    }
}
Output
Hello after 2 seconds!
⚠️

Common Pitfalls

Common mistakes include forgetting to mark a method async when using await, which causes compile errors. Another is using async void methods outside event handlers, which makes error handling difficult. Also, blocking calls like .Result or .Wait() on async tasks can cause deadlocks.

csharp
/* Wrong way: missing async keyword */
// static Task<string> GetData()
// {
//     await Task.Delay(1000); // Error: await only valid in async method
//     return "data";
// }

/* Right way: */
static async Task<string> GetData()
{
    await Task.Delay(1000);
    return "data";
}

/* Avoid async void except for event handlers */
// async void DoWork() { await Task.Delay(1000); } // Hard to catch errors

/* Prefer async Task instead */
async Task DoWorkAsync() { await Task.Delay(1000); }
📊

Quick Reference

Remember these tips when using async and await in C#:

  • Mark methods with async to use await inside.
  • Use Task or Task<T> as return types for async methods.
  • Use await to pause without blocking the thread.
  • Avoid async void except for event handlers.
  • Do not block async calls with .Result or .Wait().

Key Takeaways

Use async to mark methods that run asynchronously.
Use await to wait for tasks without blocking the program.
Async methods should return Task or Task<T>, not void.
Avoid blocking async code with synchronous waits like .Result or .Wait().
Use async/await to keep your app responsive during long-running operations.