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.
Task<int> t = Task.FromResult(42); int value = await t;
Try it
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.
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
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
asyncmethod is already running. Creating aTaskwithnew Task(...)gives a "cold" task that needsStart(); avoid it in new code. ResultandWait()block the calling thread and can deadlock under a synchronization context. Useawaitinstead.- Cache completed tasks. Return
Task.CompletedTaskor a cachedTask.FromResult(x)from non-async methods that sometimes have nothing to wait for. Do not useasyncmerely 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.Disposeis rarely needed; the garbage collector handles tasks. ContinueWithpitfalls: it usesTaskScheduler.Currentby default and does not unwrap nested tasks. Preferawait.- Task is for I/O and for waiting,
Task.Runis for pushing CPU-bound work off the calling thread. See Task.Run.