Task and Task

A Task is a promise of a value or of an end, and Task<T> is the one with a value. The previous lesson awaited one task; this one starts several, waits for all or for the first, reads a failure, and builds a task by hand when a callback has to become one.

Task.WhenAll

Task.WhenAll takes a collection of tasks and returns one task that finishes when all of them do. The results come back in the order of the array, not in the order the work finished:

var tasks = new[] { Work(1), Work(2), Work(3) }; var results = await Task.WhenAll(tasks); Console.WriteLine($"all {string.Join(",", results)}"); static async Task<int> Work(int id) { await Task.Delay(id * 5); return id * 10; }

dotnet run

all 10,20,30

The first task took five milliseconds, the second ten and the third fifteen; they finished in that order, and the array of results is still in the order the tasks were created. That is the property a report relies on: the input order survives the concurrency. A program that needs the order of completion uses WhenAny in a loop instead.

Task.WhenAny

Task.WhenAny returns the task that finishes first, which is how a program takes the fastest of several sources or applies a timeout:

var slow = Work(10); var fast = Work(20); var winner = await Task.WhenAny(slow, fast); Console.WriteLine($"winner {winner.Result}"); await Task.WhenAll(slow, fast); static async Task<int> Work(int id) { await Task.Delay(id * 5); return id * 10; }

dotnet run

winner 100

The task started with ten waited fifty milliseconds and the one started with twenty waited a hundred, so the first finished first and its result is 100. WhenAny does not cancel the loser: the second WhenAll waits for it, and a program that does not need it should cancel it with the mechanism of the next lesson.

An exception from a task

Task.Run moves work to the thread pool, and an exception thrown there is stored in the task until somebody awaits it:

var failing = Task.Run(() => throw new InvalidOperationException("task failed")); try { await failing; } catch (InvalidOperationException e) { Console.WriteLine($"caught {e.Message}"); } Console.WriteLine($"faulted {failing.IsFaulted}"); Console.WriteLine($"immediate {Task.FromResult(7).Result}");

dotnet run

caught task failed
faulted True
immediate 7

The await threw the original exception, not an AggregateException; a program that reads task.Exception instead gets the aggregate that wraps it, and task.Result on a faulted task throws the same aggregate. IsFaulted is true after the await has observed the failure, and FromResult is the cheapest way to make a completed task.

TaskCompletionSource

A callback-based API reports its end by calling a method, not by returning a task. TaskCompletionSource<T> is the bridge: the program keeps the source and completes it from the callback. A source that is cancelled and one that is completed show the two outcomes:

var cancelled = new TaskCompletionSource<int>(); cancelled.SetCanceled(); try { await cancelled.Task; } catch (TaskCanceledException) { Console.WriteLine($"canceled {cancelled.Task.IsCanceled}"); } var completed = new TaskCompletionSource<string>(); completed.SetResult("ready"); Console.WriteLine($"tcs {completed.Task.Status} {completed.Task.Result}");

dotnet run

canceled True
tcs RanToCompletion ready

The first source was cancelled before anybody awaited it, which is a completed task of the cancelled kind; the await reported it as TaskCanceledException. The second was completed with a value and its status is RanToCompletion at once. A source is completed exactly once, and a second SetResult throws InvalidOperationException, which is what protects a callback that fires twice. The next lesson cancels work that is already running.

Exercises

  1. Start five tasks with different delays and print the order in which WhenAny returns them.
  2. Make one task of a WhenAll throw and read what the exception is and what the other tasks did.
  3. Complete a TaskCompletionSource from a timer callback and await it.
  4. Call SetResult twice and read the exception.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does Task.WhenAll return?

    Answer

    A task that finishes when every task in the collection finishes

    Awaiting it waits for all of them, and the results keep the input order.

  2. In which order are the results of Task.WhenAll?

    Answer

    The order of the tasks in the collection

    The measured array was 10,20,30 although the work finished in a different order.

  3. What does this program print? var results = await Task.WhenAll(Task.FromResult(1), Task.FromResult(2)); Console.WriteLine(results[0] + results[1]);

    Answer

    3

    The two results are 1 and 2, and the sum is 3.

  4. What does Task.WhenAny return?

    Answer

    The task that finished first

    It returns one task, and the program reads its result.

  5. What does this program print? Console.WriteLine(await Task.Run(() => 21 * 2));

    Answer

    42

    Task.Run returns a Task<int> whose result is the product.

  6. What does Task.FromResult give?

    Answer

    A completed task with that result

    It is the cheap way to satisfy an API that wants a task.

  7. What does this program print? var t = Task.FromResult("x"); Console.WriteLine(t.Status);

    Answer

    RanToCompletion

    The task is complete as soon as it is made.

  8. What does awaiting a faulted task throw?

    Answer

    The original exception of the task

    The await unwraps the aggregate, which is why the catch named InvalidOperationException.

  9. What does this program print? var results = await Task.WhenAll(new[] { Task.FromResult(1), Task.FromResult(2) }); Console.WriteLine(results.Length);

    Answer

    2

    One result per task, so the array has two elements.

  10. What is a TaskCompletionSource for?

    Answer

    Turning a callback into a task that can be awaited

    The program keeps the source and completes it when the callback fires.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev