// Ausnahmebehandlung.cpp: Hauptprojektdatei.

#include "stdafx.h"

using namespace System;
using namespace System::Threading;
using namespace System::Threading::Tasks;

void tunichtgut()
{
	Thread::SpinWait(100000000);
   throw gcnew Exception("Ausnahme in Aufgabe tunichtgut()");
   Console::WriteLine("\t In tunichtgut() lief alles glatt");
}

void fehlerbehandlung(Task^ task)
{
   Console::WriteLine("\n\nFehler in Aufgabe " + task->Id
                      + ": " + task->Exception->InnerException->Message);
}

int main(array<System::String ^> ^args)
{
      Console::WriteLine("\n\n Ausnahembehandlung ");

      Task^ task = Task::Factory->StartNew(gcnew Action(tunichtgut));
      task->ContinueWith(gcnew Action<Task^>(fehlerbehandlung), TaskContinuationOptions::OnlyOnFaulted);

      try
      {
         Task^ task1 = Task::Factory->StartNew(gcnew Action(tunichtgut));
         Task^ task2 = Task::Factory->StartNew(gcnew Action(tunichtgut));

         array<Task^>^aufgaben = {task1, task2};
         Task::WaitAll(aufgaben);
      }
      catch (AggregateException^ ae)
      {
          for each (Exception^ ie in ae->InnerExceptions)
          {
              Console::WriteLine(ie->Message);
          }
      }
      
      Console::ReadLine();
      return 0;
}
