Async & Await

    Lesson 12 • Expert Track

    Write responsive, non-blocking applications with async/await and Task<T>.

    What You'll Learn

    • • Understand async, await, and Task<T>
    • • Run multiple operations concurrently
    • • Use Task.WhenAll and Task.WhenAny
    • • Handle exceptions in async methods
    • • Cancel long-running tasks with CancellationToken

    Real-World Analogy

    Imagine making breakfast. Synchronous: toast bread, wait, then brew coffee, wait. Async: start the toaster AND the coffee machine, then do something else while both work. await is you checking if each is done — you're not standing there watching.

    Running C# Locally: Install the .NET SDK or use dotnetfiddle.net.

    async/await Basics

    Mark a method with async and it can use await to pause until an operation completes — without blocking the thread. The method returns Task (for void) or Task<T> (for a value).

    Async Breakfast — Parallel Tasks

    Run toast and coffee tasks concurrently with async/await.

    Try it Yourself »
    C#
    using System;
    using System.Threading.Tasks;
    
    class Program
    {
        // async method returns Task (void) or Task<T> (with value)
        static async Task Main()
        {
            Console.WriteLine("☕ Starting breakfast...");
    
            // Start tasks concurrently
            Task<string> toastTask = MakeToastAsync();
            Task<string> coffeeTask = MakeCoffeeAsync();
    
            // await both — they run in parallel!
            string toast = await toastTask;
            string coffee = await coffeeTask;
    
            Console
    ...

    Task.WhenAll & Task.WhenAny

    Task.WhenAll waits for every task to finish — perfect for batch operations. Task.WhenAny returns the first to complete — great for racing servers or implementing timeouts.

    WhenAll & WhenAny — Concurrent Operations

    Download files in parallel and race between servers.

    Try it Yourself »
    C#
    using System;
    using System.Threading.Tasks;
    using System.Collections.Generic;
    
    class Program
    {
        static async Task Main()
        {
            Console.WriteLine("📦 Downloading files...");
    
            // Start all downloads simultaneously
            var tasks = new List<Task<string>>
            {
                DownloadFileAsync("report.pdf", 1500),
                DownloadFileAsync("photo.jpg", 800),
                DownloadFileAsync("data.csv", 2000),
                DownloadFileAsync("video.mp4", 3000)
            };
    
          
    ...

    Common Mistakes

    • Using async void: Only use async void for event handlers. Always return Task or Task<T>.
    • Blocking with .Result: Never call task.Result or task.Wait() — it can deadlock. Always use await.
    • Forgetting await: Without await, exceptions are silently swallowed and the task runs fire-and-forget.

    Exception Handling & Cancellation

    Exceptions in async code work with regular try-catch. For long-running operations, pass a CancellationToken so callers can cancel gracefully.

    Async Exceptions & Cancellation

    Handle errors and cancel operations with CancellationToken.

    Try it Yourself »
    C#
    using System;
    using System.Threading.Tasks;
    
    class Program
    {
        static async Task Main()
        {
            // Handling exceptions in async code
            try
            {
                string result = await FetchDataAsync("https://api.example.com");
                Console.WriteLine(result);
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"🌐 Network error: {ex.Message}");
            }
            catch (TimeoutException ex)
            {
                Console.WriteLine($"⏰ Timeo
    ...

    Pro Tips

    • 💡 Start tasks early and await them late — maximise concurrency.
    • 💡 Always pass CancellationToken to methods that accept it.
    • 💡 Use ConfigureAwait(false) in library code to avoid deadlocks.
    • 💡 Suffix async methods with Async by convention: GetDataAsync().

    Lesson Complete! 🎉

    You've mastered async programming in C#. Next: delegates, events, and event-driven architecture.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service