要想在主線程捕獲其他線程異常,需阻塞主線程,等所有線程執行結束,方可捕獲異常;
否則無法捕獲異常;
下面這種方式,線程拋出異常,代碼走不進catch,catch無法捕獲異常
static void GetThreadException1()
{
try
{
Task.Run(() =>
{
Console.WriteLine("dosomething");
throw new Exception("test exception");
});
Task.Run(() => Console.WriteLine("dosomething else"));
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
下面這種,catch可以捕獲到線程異常信息
static void GetThreadException2()
{
try
{
var taskList = new List<Task>();
taskList.Add( Task.Run(() =>
{
Console.WriteLine("dosomething");
throw new Exception("test exception");
}));
taskList.Add( Task.Run(() => Console.WriteLine("dosomething else")));
Task.WaitAll(taskList.ToArray());
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}