Skip to content
AgileLogics
5 min read

Multithreading with the Task Parallel Library

Prerequisites: Advanced LINQ & deferred execution

Task.Run schedules CPU-bound work on a background thread pool thread — distinct from the async/await covered in Level 2, which is primarily about waiting efficiently, not necessarily running on another thread.

Task<int> task = Task.Run(() => {
    // CPU-bound work
    return ExpensiveCalculation();
});

int result = await task;

var tasks = new List<Task<int>>();
for (int i = 0; i < 5; i++) {
    int captured = i;
    tasks.Add(Task.Run(() => captured * captured));
}
int[] results = await Task.WhenAll(tasks);

Task.WhenAll runs several tasks concurrently and waits for all of them — the C# equivalent of Java's ExecutorService submitting several Futures and collecting every result.