CSharp · Console
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
static class Program
{
static void Main()
{
var cts = new CancellationTokenSource(700);
cts.Token.Register(() => Print($"The Token was canceled."));
var options = new ParallelOptions()
{
MaxDegreeOfParallelism = 2,
CancellationToken = cts.Token
};
Print("Before starting the Parallel.Invoke.");
try
{
Parallel.Invoke(options, Enumerable.Range(1, 20).Select(i => new Action(() =>
{
Print($"Running action #{i}");
Thread.Sleep(500);
})).ToArray());
}
catch (OperationCanceledException)
{
Print("The Parallel.Invoke was canceled.");
}
}
static void Print(object value)
{
Console.WriteLine($@"{DateTime.Now:HH:mm:ss.fff} [{Thread.CurrentThread
.ManagedThreadId}] > {value}");
}
}