How do I handle concurrency in C#

Handling concurrency in C# is essential for building applications that can efficiently perform multiple tasks simultaneously. C# offers several mechanisms to manage concurrency, including threads, the Task Parallel Library (TPL), async/await, and locks to synchronize access to shared resources.

Using the Task Parallel Library (TPL) is one of the most straightforward approaches. It allows for easy creation and management of tasks, abstracting complex thread management. Here is an example of how to use TPL:

// Example of using Task Parallel Library using System; using System.Threading.Tasks; class Program { static void Main() { Task task1 = Task.Run(() => DoWork(1)); Task task2 = Task.Run(() => DoWork(2)); Task.WaitAll(task1, task2); } static void DoWork(int taskNumber) { Console.WriteLine($"Task {taskNumber} is starting."); // Simulating work Task.Delay(2000).Wait(); Console.WriteLine($"Task {taskNumber} is completed."); } }

Concurrency C# Task Parallel Library Threads Async/Await Synchronization