using System;
using System.Threading.Tasks;
using System.Threading;

namespace Syslab.Sample.Ex05
{
    class Program
    {
        static object lockObj = new object();
        static int counter = 1;
        delegate void Delegate();

        static void Main(string[] args)
        {
            CancellationTokenSource cancelSource = new CancellationTokenSource();
            ParallelOptions po = new ParallelOptions() { MaxDegreeOfParallelism = 3, CancellationToken = cancelSource.Token };

            new Thread(() => { Thread.Sleep(300); cancelSource.Cancel(); }).Start();

            try
            {
                Parallel.Invoke(po, () => { DoSomeWork(5000); }, () => { DoSomeWork(500); }, () => { DoSomeWork(100); });
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine("OPERAÇÃO CANCELADA.");
            }
        }

        static void DoSomeWork(int sleep)
        {
            int assignedTaskNumber;
            lock (lockObj) { assignedTaskNumber = counter++; }

            Console.WriteLine(string.Format("Começando a tarefa número [{0}], aguardando {1} ms.", assignedTaskNumber, sleep));
            Thread.Sleep(sleep);
            Console.WriteLine(string.Format("Terminando a tarefa número [{0}], aguardando {1} ms.", assignedTaskNumber, sleep));
        }
    }
}
