CodeBlanks Logo Icon CodeBlanks

Task.Run

C# course · Advanced · Lesson 4/83

Learn to push CPU-bound work to the background with Task.Run.

What is Task.Run?

Task.Run sends work to the thread pool and returns a Task at once. It is used to run heavy CPU work in the background so the main thread is freed.

Example: Task t = Task.Run(() => HeavyCompute());. The lambda runs on a pool thread; you wait for it with await t. Do not use Task.Run for input/output; just call an async method.

Task.Run vs await

Task.Run and await are different things. Task.Run starts a new pool thread; await waits for an already-running Task. They are often combined: await Task.Run(() => Work()).

But wrapping every async call in Task.Run is a common mistake. Async methods already run in the background; wrapping wastes a thread. Use Task.Run only for real CPU work.

Exercise Compute with Task.Run

Define static int Square(int n) returning n * n. Make Main a static async Task Main. Run the computation in the pool with int result = await Task.Run(() => Square(7)); and print it with Console.WriteLine(result);.

Show example solution
return n * n;. Make Main static async Task Main() and write int result = await Task.Run(() => Square(7)); Console.WriteLine(result);
Example solution:
using System;
using System.Threading.Tasks;

class Program
{
    static int Square(int n)
    {
        return n * n;
    }

    static async Task Main()
    {
        int result = await Task.Run(() => Square(7));
        Console.WriteLine(result);
    }
}

Test yourself

  1. Match the concepts

    Task.Run
    Sends work to the pool
    await task
    Waits for the work to finish
    CPU work
    Suitable for Task.Run
    I/O work
    Call an async method directly
  2. When is Task.Run used?

    • To wrap every async call
    • When reading from the network
    • To run heavy CPU computations in the background
    • When saving a file
    Show answer

    To run heavy CPU computations in the background — Correct. Task.Run is for heavy CPU work in the background.

  3. Complete the Task.Run call

    Task t = Task.____(() => Work());
    Show answer
    Task t = Task.Run(() => Work());

All lessons in Advanced