Sobes.tech
Junior — Middle

How to implement parallel execution of multiple tasks in a program?

sobes.tech AI

Answer from AI

In C#, to perform multiple tasks in parallel, you can use:

  • The Task class from the System.Threading.Tasks namespace.
  • async/await for asynchronous programming.
  • Parallel.For or Parallel.ForEach for parallel loops.

Example of running multiple tasks in parallel:

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Task task1 = Task.Run(() => DoWork(1));
        Task task2 = Task.Run(() => DoWork(2));

        await Task.WhenAll(task1, task2);
        Console.WriteLine("All tasks completed");
    }

    static void DoWork(int id)
    {
        Console.WriteLine($"Task {id} started working");
        Task.Delay(1000).Wait();
        Console.WriteLine($"Task {id} completed");
    }
}

This allows efficient use of processor resources and improves program performance.