Task Parallel Library in C#
Introduction
The Task Parallel Library (TPL) is a set of public types and APIs in the .NET Framework that support parallel programming. The TPL scales the degree of concurrency dynamically to most efficiently use all the processors that are available. The core of the TPL is based on the concept of a Task, which represents an asynchronous operation.
Getting Started with Task Parallel Library
To start using the Task Parallel Library, ensure you have a working installation of .NET. You can create a new C# console application in Visual Studio or use the .NET CLI to create a new project.
Using .NET CLI to create a new project:
dotnet new console -n TaskParallelLibraryDemo
Creating and Running Tasks
A Task
in C# represents an asynchronous operation. You can create and start a new task using the Task.Run
method. Below is a simple example:
Example:
using System; using System.Threading.Tasks; class Program { static void Main() { Task task = Task.Run(() => { for (int i = 0; i < 10; i++) { Console.WriteLine($"Task iteration {i}"); } }); task.Wait(); // Wait for the task to complete Console.WriteLine("Task completed."); } }
Output:
Task iteration 0 Task iteration 1 Task iteration 2 Task iteration 3 Task iteration 4 Task iteration 5 Task iteration 6 Task iteration 7 Task iteration 8 Task iteration 9 Task completed.
Handling Task Results
Tasks can return values. You can use the Task<TResult>
class to represent a task that returns a value. Below is an example:
Example:
using System; using System.Threading.Tasks; class Program { static void Main() { Tasktask = Task.Run(() => { int sum = 0; for (int i = 1; i <= 10; i++) { sum += i; } return sum; }); Console.WriteLine($"Sum: {task.Result}"); // Wait and get the result } }
Output:
Sum: 55
Continuations with Tasks
Tasks support continuation, which allows you to run a task after another task completes. You can use the ContinueWith
method to set up a continuation task.
Example:
using System; using System.Threading.Tasks; class Program { static void Main() { Tasktask = Task.Run(() => { int sum = 0; for (int i = 1; i <= 10; i++) { sum += i; } return sum; }); task.ContinueWith(t => { Console.WriteLine($"Sum: {t.Result}"); }); task.Wait(); // Wait for the first task to complete } }
Output:
Sum: 55
Handling Exceptions in Tasks
Exceptions in tasks can be handled using the try-catch
block inside the task or by catching the AggregateException
outside the task. Below is an example:
Example:
using System; using System.Threading.Tasks; class Program { static void Main() { Task task = Task.Run(() => { throw new InvalidOperationException("An error occurred in the task."); }); try { task.Wait(); } catch (AggregateException ex) { foreach (var innerEx in ex.InnerExceptions) { Console.WriteLine(innerEx.Message); } } } }
Output:
An error occurred in the task.
Using Task.Delay for Asynchronous Waits
The Task.Delay
method creates a task that completes after a time delay. This can be useful for creating non-blocking waits in asynchronous code. Below is an example:
Example:
using System; using System.Threading.Tasks; class Program { static async Task Main() { Console.WriteLine("Waiting for 2 seconds..."); await Task.Delay(2000); Console.WriteLine("Wait completed."); } }
Output:
Waiting for 2 seconds... Wait completed.
Conclusion
The Task Parallel Library (TPL) is a powerful tool for creating and managing asynchronous operations in C#. It simplifies parallel programming and helps utilize system resources more effectively. By using tasks, continuations, and proper exception handling, you can write efficient and robust asynchronous code.