Task (System.Threading.Tasks.Task)
Overview
The Task class represents an asynchronous operation. It is the core building block of the Task Parallel Library (TPL) and provides a high‑level abstraction over threads, enabling developers to write scalable, responsive applications.
Typical scenarios include I/O‑bound work, CPU‑bound parallelism, and composing asynchronous pipelines.
Basic Usage
Running a simple asynchronous method returning a Task:
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
await PerformWorkAsync();
Console.WriteLine("Work completed.");
}
static async Task PerformWorkAsync()
{
await Task.Delay(2000); // Simulate async work
Console.WriteLine("Async operation finished.");
}
}
Creating and Starting Tasks
Explicit Task creation using Task.Run or the Task constructor:
Task computeTask = Task.Run(() =>
{
// CPU‑bound work
int result = 0;
for (int i = 0; i < 1_000_000; i++) result += i;
return result;
});
int sum = await computeTask;
Console.WriteLine($"Sum = {sum}");
Continuations
Chain tasks using ContinueWith or await syntax for cleaner code:
Task.Run(() => GetDataAsync())
.ContinueWith(prev => ProcessData(prev.Result))
.ContinueWith(_ => Console.WriteLine("All done."));
// Using await for the same flow
async Task Flow()
{
var data = await GetDataAsync();
ProcessData(data);
Console.WriteLine("All done.");
}
Exception Handling
Exceptions are captured by the Task and re‑thrown when awaited. Use try/catch around await or inspect Task.Exception for aggregated errors.
try
{
await Task.Run(() => { throw new InvalidOperationException("Bad thing"); });
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Handled: {ex.Message}");
}