| Threading in C# | Asynchronous Programming with async/await in C# | |
Task Parallel Library (TPL) in C# |
The Task Parallel Library (TPL) is a set of APIs within the System.Threading.Tasks namespace that simplifies adding parallelism and concurrency to C# applications. Introduced in .NET Framework 4.0, it provides a task-based model that is more efficient and scalable than traditional thread management.
Instead of manually creating and managing threads, the TPL uses a thread pool and automatically balances the workload across available processor cores. It manages complexities such as work partitioning, scheduling, load balancing, and exception handling.
The Task class represents a single asynchronous operation. The generic Task<TResult> represents a task that returns a result of type TResult.
using System;
using System.Threading.Tasks;
public class TaskExample
{
public static void Main()
{
// Create and start a task that returns a result
Task taskWithResult = Task.Run(() =>
{
Console.WriteLine("Task is calculating...");
return 10 * 10;
});
// Wait for the task to complete and get the result
int result = taskWithResult.Result;
Console.WriteLine($"Result from task: {result}");
}
}
The Parallel class provides static methods for executing loops in parallel, simplifying the process of parallelizing for and foreach loops.
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
public class ParallelExample
{
public static void Main()
{
var items = new List { 1, 2, 3, 4, 5 };
// Execute a loop in parallel
Parallel.ForEach(items, item =>
{
Console.WriteLine($"Processing item {item} on thread {Task.CurrentId}");
});
}
}
Action delegates in parallel.Introduced in C# 5.0, async and await are built on top of the TPL, making asynchronous programming simpler and more readable. await pauses method execution until a Task completes without blocking the thread, ideal for I/O-bound tasks.
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class AsyncExample
{
public static async Task Main()
{
Console.WriteLine("Main thread started.");
var httpClient = new HttpClient();
// Await the completion of an I/O-bound task
string html = await httpClient.GetStringAsync("https://example.com");
Console.WriteLine($"Web page downloaded. HTML length: {html.Length}");
Console.WriteLine("Main thread finished.");
}
}
The TPL provides methods to coordinate multiple tasks:
The Task Parallel Library (TPL) is a set of public types and APIs in the System.Threading and System.Threading.Tasks namespaces that simplify writing multithreaded and parallel code. It abstracts away the complexity of thread management, making it easier to write scalable and efficient applications.
π TPL was introduced in .NET Framework 4.0, released in 2010. It has since become the preferred way to write parallel and asynchronous code in .NET, including .NET Core and .NET 5+.
Task, Task<T>)Parallel.For, Parallel.ForEach)Task.WhenAll, Task.WhenAny)CancellationToken)
Task task = Task.Run(() => Console.WriteLine("Running in parallel"));
Parallel.For(0, 5, i => Console.WriteLine($"Iteration {i}"));
Task<int> task = Task.Run(() => 42); int result = task.Result; // Blocks until completed
Task.WhenAll(
Task.Run(() => Console.WriteLine("Task 1")),
Task.Run(() => Console.WriteLine("Task 2"))
).Wait();
var cts = new CancellationTokenSource();
Task.Run(() => {
while (!cts.Token.IsCancellationRequested) {
Console.WriteLine("Working...");
}
}, cts.Token);
cts.Cancel(); // Request cancellation
async/await with Task for asynchronous workflows.Task.Run over manually creating threads.ConfigureAwait(false) in library code to avoid deadlocks..Wait() or .Result in async code.CancellationToken for cooperative cancellation.async/await instead.AggregateException when using Task.Wait() or .Result.async/awaitAggregateException.CancellationTokenSource.async/await instead of Parallel constructs.The Task Parallel Library (TPL) revolutionized how developers write concurrent code in C#. Introduced in .NET Framework 4.0, it provides a high-level, flexible, and efficient model for parallelism. Whether you're building desktop apps, web services, or data pipelines, TPL helps you harness the power of modern multicore processors with minimal effort.
| Threading in C# | Asynchronous Programming with async/await in C# | |