ParallelForEachLoopCancel

CSharp · Console

/Program.cs

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
					
public class Program
{
	public static void Main()
	{
		int[] nums = Enumerable.Range(0, 100000).ToArray();
		CancellationTokenSource cts = new CancellationTokenSource();

		// Use ParallelOptions instance to store the CancellationToken
		ParallelOptions po = new ParallelOptions();
		po.CancellationToken = cts.Token;
		po.MaxDegreeOfParallelism = System.Environment.ProcessorCount;
		Console.WriteLine($"ProcessorCount: {System.Environment.ProcessorCount}");

		// Run a task so that we can cancel from another thread.
		Task.Factory.StartNew(async () =>
		{
			Console.WriteLine($"Task started {DateTime.Now}");
			await Task.Delay(10);
			cts.Cancel();
			Console.WriteLine($"Task ended {DateTime.Now}");
		});

		try
		{
			Console.WriteLine($"Parallel started {DateTime.Now}");
			Parallel.ForEach(nums, po, (num) =>
			{
				double d = Math.Sqrt(num);
				Console.WriteLine($"Sqrt of {num} is {d} on {Thread.CurrentThread.ManagedThreadId}");
			});
			Console.WriteLine($"Parallel ended {DateTime.Now}");
		}
		catch (OperationCanceledException e)
		{
			Console.WriteLine(e.Message);
		}
		finally
		{
			cts.Dispose();
		}
	}
}
;