- 1 year ago
Start multiple tasks in parallel and wait for them in windows?
To start multiple tasks in parallel and wait for them to complete in a Windows application, you can use the Task Parallel Library (TPL) provided by .NET Framework or .NET Core. This library simplifies the creation and management of parallel tasks. Here's how you can achieve this:
Using .NET Framework (.NET Core follows a similar approach):
In a C# application, you can use the
Task.WhenAll
method to start multiple tasks concurrently and wait for all of them to complete. Here's an example:csharpusing System;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
Task[] tasks = new Task[3];
// Start multiple tasks
tasks[0] = Task.Run(() => DoWork(1));
tasks[1] = Task.Run(() => DoWork(2));
tasks[2] = Task.Run(() => DoWork(3));
// Wait for all tasks to complete
Task.WhenAll(tasks).Wait();
Console.WriteLine("All tasks have completed.");
}
static void DoWork(int id)
{
Console.WriteLine($"Task {id} is starting...");
// Simulate some work
Task.Delay(1000 * id).Wait();
Console.WriteLine($"Task {id} has completed.");
}
}
In this example,
Task.Run
is used to start tasks concurrently, andTask.WhenAll(tasks).Wait()
is used to wait for all tasks to complete.Using Async/Await (Preferred in Modern C# Applications):
In modern C# applications, you can also use
async
andawait
to achieve parallelism in a more readable and efficient way:csharpusing System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
await Task.WhenAll(
DoWorkAsync(1),
DoWorkAsync(2),
DoWorkAsync(3)
);
Console.WriteLine("All tasks have completed.");
}
static async Task DoWorkAsync(int id)
{
Console.WriteLine($"Task {id} is starting...");
// Simulate some asynchronous work
await Task.Delay(1000 * id);
Console.WriteLine($"Task {id} has completed.");
}
}
In this version,
async
andawait
keywords make the code more readable and allow for better utilization of resources.
Both of these examples demonstrate how to start tasks in parallel and wait for their completion. Choose the approach that aligns with the version of .NET you are using and your programming preferences.