Why doesn't Task.WaitAny throw exception? [dup

2019-04-22 02:13发布

This question already has an answer here:

In the following code "Inside catch block" is never printed. "Final line" is printed though. Why so? Please help.

Task task1 = Task.Factory.StartNew(() =>
{                
    throw new Exception("some exception");             
});

try
{
    Task.WaitAny(new Task[] { task1 });
}
catch(Exception e)
{
    Console.WriteLine("Inside catch block.");
}

Console.WriteLine("Final line.");

1条回答
不美不萌又怎样
2楼-- · 2019-04-22 02:26

This is because your code executing in a different thread,but you can catch the exception occurred in a different thread using the following code

Task task1 = Task.Factory.StartNew(() =>
{
    throw new Exception("some exception");
});

try
{
    task1.Wait();
}
catch (AggregateException ex)
{
    Console.WriteLine(ex);
}
查看更多
登录 后发表回答