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

namespace Ausnahmebehandlung
{
    class Program
    {
        public static void UnreliableOperation()
        {
            Console.WriteLine("\n Aufgabe");
            Random generator = new Random();
            Thread.SpinWait(100000000);

            if (generator.Next(2) == 1)
                throw new Exception("\t Ausnahme in Aufgabe");
            else
                Console.WriteLine("\t In Aufgabe lief alles glatt");
        }

        public static void TreatError(Task t)
        {
            Console.WriteLine("\n Fortsetzung");
            if (t.Exception != null)
            {
                Console.WriteLine("\n\t Fehler in der Aufgabe mit der ID " + t.Id);
                Console.WriteLine("\n\t Original-Text: " + t.Exception.InnerException.Message);
            }
        }


        static void Main(string[] args)
        {

            Task task1 = Task.Factory.StartNew(UnreliableOperation);
            Task task2 = Task.Factory.StartNew(UnreliableOperation);
            Task task3 = Task.Factory.StartNew(UnreliableOperation);

            task1.ContinueWith(TreatError, TaskContinuationOptions.OnlyOnFaulted);
            task2.ContinueWith(TreatError, TaskContinuationOptions.OnlyOnFaulted);
            task3.ContinueWith(TreatError, TaskContinuationOptions.OnlyOnFaulted);
      
            Console.ReadLine();
        }
    }
}
