Junior — Middle
How is the execution of tasks implemented in parallel in programming?
sobes.tech AI
Answer from AI
In C#, parallel execution of tasks is implemented using several approaches:
- Threads — creating and managing threads manually through the
Threadclass. - ThreadPool — using a pool of threads for reuse without the overhead of creating new threads.
- Tasks — a higher-level abstract mechanism from the
System.Threading.Tasksnamespace that allows running asynchronous operations. - Async/Await — simplifies writing asynchronous code, enabling tasks to run in parallel without blocking the main thread.
Example of parallel execution using Task:
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
Task task1 = Task.Run(() => {
// Some parallel work
Console.WriteLine("Task 1 is running");
});
Task task2 = Task.Run(() => {
Console.WriteLine("Task 2 is running");
});
await Task.WhenAll(task1, task2);
Console.WriteLine("All tasks are completed");
}
}
Thus, parallelism is achieved by running multiple tasks that can execute simultaneously on different threads.