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.
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.");
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?