Parallel
Key Features of Parallel:
Example Illustrating Parallel Usage in C#
using System;
using System.Threading.Tasks;
public class Program
{
public static void Main()
{
// Example using Parallel.For to iterate over a range of values
Parallel.For(0, 10, i =>
{
Console.WriteLine($"Task {i} is executing on thread {Task.CurrentId}");
// Simulate some work
Task.Delay(100).Wait();
});
Console.WriteLine("Parallel.For has completed.");
// Example using Parallel.ForEach to iterate over an array
string[] names = { "Alice", "Bob", "Charlie", "David" };
Parallel.ForEach(names, name =>
{
Console.WriteLine($"Hello, {name}!");
// Simulate some work
Task.Delay(100).Wait();
});
Console.WriteLine("Parallel.ForEach has completed.");
// Example using Parallel.Invoke to execute multiple actions in parallel
Parallel.Invoke(
() => DoWork("Task 1"),
() => DoWork("Task 2"),
() => DoWork("Task 3")
);
Console.WriteLine("Parallel.Invoke has completed.");
}
private static void DoWork(string taskName)
{
Console.WriteLine($"{taskName} is executing on thread {Task.CurrentId}");
// Simulate some work
Task.Delay(100).Wait();
Console.WriteLine($"{taskName} has completed.");
}
}Detailed Explanation
Summary
Last updated