How do I use the Task Parallel Library (TPL)

The Task Parallel Library (TPL) is a set of public types and APIs in the System.Threading.Tasks namespace. It simplifies the process of writing parallel and asynchronous code in C#. With TPL, you can create and manage tasks, enabling you to efficiently execute code concurrently. This leads to improved performance and responsiveness in applications.

Task Parallel Library, TPL, C#, parallel programming, asynchronous programming, multithreading
Learn how to use the Task Parallel Library in C# for efficient parallel programming and asynchronous task management.

Here is an example demonstrating how to use TPL to run tasks in parallel:

using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Task task1 = Task.Run(() => { // Simulate a time-consuming task for (int i = 0; i < 5; i++) { Console.WriteLine("Task 1 - Count: " + i); Task.Delay(1000).Wait(); // wait for 1 second } }); Task task2 = Task.Run(() => { // Simulate a different time-consuming task for (int i = 0; i < 5; i++) { Console.WriteLine("Task 2 - Count: " + i); Task.Delay(500).Wait(); // wait for 0.5 seconds } }); Task.WaitAll(task1, task2); // Wait for both tasks to complete Console.WriteLine("Both tasks completed."); } }

Task Parallel Library TPL C# parallel programming asynchronous programming multithreading