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

Task

A Task is a promise that some work will finish later, like a pager that buzzes when your table is ready. It represents a job running in the background that gives no result.

In this page:

  1. Task
Syntax
csharp
static async Task MethodNameAsync()
{
    await Task.Delay(milliseconds);
}

Task task = MethodNameAsync();
await 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");
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting to await a Task, so exceptions are lost and work is not finished.
  2. Using Task.Run for I/O work when async APIs exist.
  3. Using Thread.Sleep in async code instead of await Task.Delay.
🔒

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.