Task.WaitAll
method can throw an AggregateException
, but Task.WaitAny
method does not.
Questions:
- I do not understand for what purpose the developers of the framework did this?
- How to catch an exception from a task using
Task.WaitAny
method?
Example:
using System;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
void MyMethodForDivideByZeroException()
{
int a = 1;
a = a / 0;
}
void MyMethodForIndexOutOfRangeException()
{
int[] MyArrayForInt = new int[2] { 1, 2 };
Console.WriteLine(MyArrayForInt[2]);
}
Task MyTask22 = new Task(MyMethodForDivideByZeroException);
Task MyTask23 = new Task(MyMethodForIndexOutOfRangeException);
MyTask22.Start();
MyTask23.Start();
Task.WaitAny(MyTask22, MyTask23); //No exceptions
//Task.WaitAll(MyTask22, MyTask23); //AggregateException
Console.WriteLine(MyTask22.Status);
Console.WriteLine(MyTask23.Status);
}
}
}