捕获单独线程中抛出的异常
在多线程应用程序中,处理单独线程中发生的异常至关重要。本指南将演示实现此目的的两种方法。
.NET 4 及更高版本中基于任务的异常处理
考虑使用 Task
Task<int> task = new Task<int>(Test); task.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted); task.Start(); ... static void ExceptionHandler(Task<int> task) { Console.WriteLine(task.Exception.Message); }
Task<int> task = new Task<int>(Test); task.Start(); try { task.Wait(); } catch (AggregateException ex) { Console.WriteLine(ex); }
.NET 3.5 中的异常处理
对于 .NET 3.5,请考虑以下方法:
Exception exception = null; Thread thread = new Thread(() => Test(0, 0)); thread.Start(); thread.Join(); if (exception != null) Console.WriteLine(exception);
Exception exception = null; Thread thread = new Thread(() => { try { Test(0, 0); } catch (Exception ex) { lock (exceptionLock) { exception = ex; } } }); thread.Start(); thread.Join(); if (exception != null) Console.WriteLine(exception);
以上是如何从 .NET 中的单独线程捕获异常?的详细内容。更多信息请关注PHP中文网其他相关文章!