CodeBlanks Logo Icon CodeBlanks

The Task class

C# course · Advanced · Lesson 2/83

Learn the asynchronous operation represented by Task.

The Task class

The Task class represents background work in C#. Use Task for operations that return no result, and Task<T> for ones that do. A Task may be running, completed, or faulted.

To produce an already-completed Task, write Task.FromResult(42); this gives a result with no real waiting. For an empty Task use Task.CompletedTask. These are useful in tests and deterministic flows.

Using Task<T>

To get the result of a Task<T> you use await: int n = await t;. When t completes, its Result property holds the value; await unwraps it safely.

Writing t.Result directly causes a synchronous wait that can deadlock. So always read the result through await. If the task faulted, await rethrows the exception.

Exercise Return a value with Task.FromResult

Define a static Task<int> GetAge() method. In its body return Task.FromResult(30). Make Main a static async Task Main; read the result with int age = await GetAge(); and print it with Console.WriteLine(age);.

Show example solution
In the body write return Task.FromResult(30);. In Main write int age = await GetAge(); Console.WriteLine(age);
Example solution:
using System;
using System.Threading.Tasks;

class Program
{
    static Task<int> GetAge()
    {
        return Task.FromResult(30);
    }

    static async Task Main()
    {
        int age = await GetAge();
        Console.WriteLine(age);
    }
}

Test yourself

  1. Create a Task<int>

    Task<int> t = Task.____(42);
    Show answer
    Task<int> t = Task.FromResult(42);
  2. Match each Task member to its role

    Task.CompletedTask
    Empty, completed Task
    Task.FromResult(42)
    Ready result Task
    Task.Run(...)
    Sends work to the pool
    Task.Delay(100)
    Waits on a timer
  3. What does Task.CompletedTask represent?

    • A running Task
    • A cancelled Task
    • A faulted Task
    • An already completed empty Task
    Show answer

    An already completed empty Task — Correct. Task.CompletedTask is a completed empty Task.

All lessons in Advanced