在 .NET 4
及更高版本中,您可以使用
Task<T>class而不是创建新线程。然后,您可以使用
.Exceptions任务对象上的属性获取异常。有两种方法可以做到这一点:
在单独的方法中://您在某些 任务的 线程中处理异常
class Program
{
static void Main(string[] args)
{
Tasktask = new Task (Test);
task.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted);
task.Start();
Console.ReadLine();
}static int Test(){ throw new Exception();}static void ExceptionHandler(Task<int> task){ var exception = task.Exception; Console.WriteLine(exception);}}
用相同的方法://您在 调用者的 线程中处理异常
class Program
{
static void Main(string[] args)
{
Tasktask = new Task (Test);
task.Start();try { task.Wait(); } catch (AggregateException ex) { Console.WriteLine(ex); } Console.ReadLine();}static int Test(){ throw new Exception();}}
请注意,您得到的异常是
AggregateException。所有实际的异常都可以通过
ex.InnerExceptions属性获得。
在 .NET 3.5中, 您可以使用以下代码:
//您在 子 线程中处理异常
class Program
{
static void Main(string[] args)
{
Exception exception = null;
Thread thread = new Thread(() => SafeExecute(() => Test(0, 0), Handler));
thread.Start();Console.ReadLine();}private static void Handler(Exception exception){ Console.WriteLine(exception);}private static void SafeExecute(Action test, Action<Exception> handler){ try { test.Invoke(); } catch (Exception ex) { Handler(ex); }}static void Test(int a, int b){ throw new Exception();}}
或//您在 调用者的 线程中处理异常
class Program
{
static void Main(string[] args)
{
Exception exception = null;
Thread thread = new Thread(() => SafeExecute(() => Test(0, 0), out exception));thread.Start(); thread.Join(); Console.WriteLine(exception); Console.ReadLine();}private static void SafeExecute(Action test, out Exception exception){ exception = null; try { test.Invoke(); } catch (Exception ex) { exception = ex; }}static void Test(int a, int b){ throw new Exception();}}



