← Back to C# Course | Chapter 13: Async Programming | Lesson 2 of 6

Task

In this page:

  1. Task

Task

Task represents an asynchronous operation that doesn't produce a value, similar to how void methods don't return one synchronously. You can await a Task to know when it finishes, or use Task.Run to offload CPU-bound work to a background thread. Tasks can be composed with Task.WhenAll and Task.WhenAny.

Note: Task.Run(() => ...) is for CPU-bound work; await alone is enough for naturally asynchronous I/O.

Example: Task

markup
using System;
using System.Threading.Tasks;

class Program
{
    static async Task DoWorkAsync()
    {
        await Task.Delay(50);
        Console.WriteLine("Work done");
    }

    static async Task Main(string[] args)
    {
        Task t1 = DoWorkAsync();
        Task t2 = DoWorkAsync();

        await Task.WhenAll(t1, t2);
        Console.WriteLine("Both tasks finished");
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.