Skip to content
Tutorials Center
My learning

Topics

Lesson 96 of 182 ยท Async and Concurrency

Tasks and the Task Parallel Library

Learn C# tasks - Task.Run, Task<T>, Wait and Result pitfalls, continuations, exceptions inside tasks, TaskCompletionSource and Task.Delay, with runnable examples.

A thread is a worker. A task is a promise of a result. When you start a task you are saying "do this piece of work somehow, and give me an object that tells me when it is finished, what it produced, or what went wrong". The Task and Task<T> classes (in System.Threading.Tasks, called the Task Parallel Library or TPL) are the foundation of every modern .NET concurrency API, including async/await.

A task is not a thread. A CPU-bound task usually runs on a thread-pool thread, but many tasks (waiting for a timer, a network reply or a file) use no thread at all while they wait. Thinking of a task as "a value that will exist in the future" is the right mental model. This lesson covers creating tasks, getting results, the traps with Wait and Result, continuations, errors, TaskCompletionSource and Task.Delay. The next lesson, async and await, makes all of it read like ordinary code.

Task.Run and Task

Task.Run queues a delegate on the thread pool and returns immediately with a task. A Task has no result; a Task<T> produces a value of type T.

C# Task.Run with and without a result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Wait() blocks until the task is done. .Result blocks until the task is done and then returns the value. After completion, Status is RanToCompletion. Other statuses you will meet: Running, WaitingForActivation (for promise-style tasks), Faulted (an exception happened) and Canceled.

The workhorse rule: use Task.Run for CPU-bound work you want off the current thread. Do not wrap I/O in Task.Run; use the async APIs that exist for I/O (HttpClient.GetStringAsync, File.ReadAllTextAsync...).

Blocking with Wait and Result

Calling Wait() or .Result blocks the calling thread. In a console program that is often fine, and the examples here use it so you can see the results. In a UI application or in older ASP.NET it can deadlock: the blocked thread is the one the task needs in order to finish. In any server it wastes a thread that could have served another request. The rule for application code is: prefer await (next lesson) over Wait and Result; use blocking calls only at the very top of a program or in tests.

Wait and Result also change how exceptions look, as we see below.

Several tasks at once

Because a task starts as soon as you create it, starting several and collecting them later gives you real concurrency.

C# Starting tasks first, collecting results later

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Task.WaitAll blocks until all tasks finish. Because we kept the tasks in an array in a fixed order, the output order is deterministic even though the tasks may run in any order. On our single-CPU server they run one after another; on a multi-core machine they would truly overlap. The next lesson shows the non-blocking version, await Task.WhenAll.

Continuations

A continuation is "when this task finishes, run that code next". ContinueWith attaches one and itself returns a task, so you can chain steps.

C# Chaining work with ContinueWith

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Continuations work, but chains of ContinueWith get ugly fast (nesting, error handling per step, thread-affinity surprises). await replaces nearly all of them. Know ContinueWith so you can read older code; write await in new code.

Exceptions inside tasks

An exception thrown inside a task does not crash the program the way it would on a raw thread. The task catches it, moves to Faulted, and stores the exception. It reappears when you ask for the outcome. If you used Wait(), Result or WaitAll, the exception is wrapped in an AggregateException, because a task can fail with several errors (for example, when it has child tasks).

C# AggregateException from Result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The outer exception is an AggregateException and the real error (DivideByZeroException: "Attempted to divide by zero.") sits in InnerException. With await you get the original exception directly, with no wrapper, which is another reason to prefer it.

If nobody ever observes a faulted task (no Wait, no Result, no await), the exception is silently dropped on modern .NET. It no longer crashes the process, but the error is lost. Always observe the tasks you start.

TaskCompletionSource: a task you finish yourself

Task.Run creates a task that runs code. Sometimes there is no code to run, only an event to wait for: a callback, a button click, a message arriving. TaskCompletionSource<T> creates a task whose completion you control by hand: SetResult, SetException or SetCanceled.

C# Turning a callback into a task

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

This is how old callback-style and event-style APIs are wrapped so they can be awaited. Always pass RunContinuationsAsynchronously: without it, code waiting on your task can run inside the SetResult call, on your thread, while you still hold locks, which causes some very confusing bugs. Complete the source exactly once; a second SetResult throws, and TrySetResult returns false instead.

Task.Delay and Task.FromResult

Task.Delay(ms) returns a task that completes after a time without blocking any thread (unlike Thread.Sleep). Task.FromResult(x) returns an already-completed task, handy when an interface demands a task but you have the answer already. Task.CompletedTask is the same for no result.

C# Delay does not block a thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Both delays run at the same time, so the program waits about 200 ms in total, not 400. We print only whether they overlapped, never the raw timing, because exact milliseconds vary from run to run.

Inspecting a task: Id, AsyncState, CurrentId and RunSynchronously

A Task carries a few properties that help with diagnosing and tracing work.

  • Id is a number the runtime assigns when the task object is created. It is unique inside the process, but it is not a thread id and the exact values are not guaranteed.
  • Task.CurrentId returns the id of the task whose code is running right now, or null when you are not inside a task.
  • AsyncState holds the optional object you passed as the state argument of the older new Task(action, state) and ContinueWith overloads. Modern code uses lambda captures instead, so you will mostly see it in older libraries.
  • IsCompleted, IsCompletedSuccessfully, IsFaulted and IsCanceled answer the question "what happened?" without comparing Status values.
  • RunSynchronously() runs a task that has not been started yet on the calling thread (the scheduler may still decide otherwise) and returns when it is done. Use it only for cold tasks you created with the Task constructor; a task from Task.Run is already started and RunSynchronously throws InvalidOperationException.
C# Task properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A task you create with new Task(...) stays in the Created state until you call Start() or RunSynchronously(). Forgetting that is a classic way to build a task that never finishes. Prefer Task.Run, which creates and starts in one step.

Parallel work: when to use what

Task.Run gives you one background job. To spread a loop over many cores, use Parallel.For and PLINQ. To wait for many tasks without blocking, combine them with WhenAll and WhenAny. To stop them early, pass a CancellationToken.

Pitfalls checklist:

  • Do not call Result or Wait() inside code that can run on a UI or request thread; you may deadlock.
  • Do not start a task and forget it: unobserved exceptions vanish.
  • Do not use Task.Run just to "make something async"; that moves a synchronous call to another thread and gains nothing for I/O.
  • Do not share mutable state between tasks without protection; see Threads and synchronization.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a Task<int>?

    A task is a promise of a future result (or error). It may or may not use a thread while it runs.
  2. 2. A task throws DivideByZeroException, and you read task.Result. What do you catch?

    Wait, Result and WaitAll wrap task errors in an AggregateException. Await would rethrow the original exception.
  3. 3. Why is Task.Delay(1000) better than Thread.Sleep(1000) inside asynchronous code?

    Task.Delay returns a task that completes after the time; no thread sits blocked while waiting.
  4. 4. When do you use TaskCompletionSource<T>?

    It lets you hand out a Task and complete it later with SetResult, SetException or SetCanceled.
  5. 5. What is the main problem with calling .Result on a task in a UI application?

    The UI thread waits for the task while the task's continuation needs the UI thread. Neither can proceed.

Summary

  • A Task represents future work; Task<T> also produces a value. It is not the same as a thread.
  • Task.Run queues CPU-bound work on the thread pool. Do not wrap I/O in it.
  • Wait, Result and WaitAll block, and wrap errors in AggregateException. Prefer await in application code.
  • ContinueWith chains steps; await is nearly always clearer.
  • TaskCompletionSource<T> turns callbacks and events into tasks; Task.Delay waits without a thread; Task.FromResult returns a finished task.
  • Always observe your tasks, or their errors are lost.

Next: async and await