Welcome to the .NET Tasks Documentation
Tasks are the primary way to work with asynchronous operations in .NET. They provide a powerful abstraction over Thread
handling, enable composition, and simplify error handling.
Quick Start
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
int result = await ComputeAsync(5);
Console.WriteLine($"Result: {result}");
}
static Task<int> ComputeAsync(int value) =>
Task.Run(() => {
// Simulate work
Thread.Sleep(1000);
return value * value;
});
}
Run the example above to see a basic asynchronous computation using Task.Run
and await
.
Key Concepts
- Task Lifecycle: Created → Running → RanToCompletion / Faulted / Canceled.
- Continuation: Use
.ContinueWith
orawait
to chain tasks. - Exception Handling: Exceptions are captured and re‑thrown when awaited.
- Cancellation: Leverage
CancellationToken
to abort work cooperatively.