Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Async and Concurrency

Task and Task<T>

Reference for Task and Task<TResult> in C#: create completed and running tasks, read status and results, handle faults and chain continuations.

A Task represents one operation that may still be running. It is a promise: it starts out incomplete and finishes exactly once, either successfully, with an exception (faulted) or because it was cancelled. Task<TResult> is the same thing that also carries a result value.

You rarely create tasks yourself. Most of the time an async method or a library call hands you one, and you await it. The members below matter when you need to inspect a task, build a completed one, or attach work to it by hand.

C#
Task<int> t = Task.FromResult(42);
int value = await t;

Try it

C# Completed tasks and their status

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.

C# Running work and continuations

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.

Syntax

C#
public class Task : IAsyncResult, IDisposable
{
    public TaskStatus Status { get; }
    public bool IsCompleted { get; }
    public bool IsCompletedSuccessfully { get; }
    public bool IsFaulted { get; }
    public bool IsCanceled { get; }
    public AggregateException? Exception { get; }
    public static Task CompletedTask { get; }
    public static Task<TResult> FromResult<TResult>(TResult result);
    public static Task FromException(Exception exception);
    public static Task FromCanceled(CancellationToken token);
    public static Task Run(Action action);
    public static Task<TResult> Run<TResult>(Func<TResult> function);
    public Task ContinueWith(Action<Task> continuation);
    public void Wait();
}

public class Task<TResult> : Task
{
    public TResult Result { get; }
}
Member Description
Status One of Created, WaitingForActivation, WaitingToRun, Running, WaitingForChildrenToComplete, RanToCompletion, Canceled, Faulted.
IsCompleted true once the task is in any of the three final states (success, fault or cancellation).
IsCompletedSuccessfully true only for RanToCompletion.
Exception An AggregateException holding every exception, or null.
Result The result of a Task<TResult>; blocks until it is available.
FromResult, FromException, FromCanceled, CompletedTask Create tasks that are already finished.

Returns: Task.Run returns a task that is queued on the thread pool.

Errors: await rethrows the first stored exception as is. Wait() and Result wrap it in an AggregateException. A cancelled task throws TaskCanceledException when awaited.

Usage notes

  • Hot tasks. A task you receive from an async method is already running. Creating a Task with new Task(...) gives a "cold" task that needs Start(); avoid it in new code.
  • Result and Wait() block the calling thread and can deadlock under a synchronization context. Use await instead.
  • Cache completed tasks. Return Task.CompletedTask or a cached Task.FromResult(x) from non-async methods that sometimes have nothing to wait for. Do not use async merely to wrap a value.
  • Unobserved exceptions. A faulted task that is never awaited keeps its exception silently. Always await tasks you start, or store them.
  • Do not dispose tasks routinely. Task.Dispose is rarely needed; the garbage collector handles tasks.
  • ContinueWith pitfalls: it uses TaskScheduler.Current by default and does not unwrap nested tasks. Prefer await.
  • Task is for I/O and for waiting, Task.Run is for pushing CPU-bound work off the calling thread. See Task.Run.