我的方法之一 (Method1
) 产生了一个新线程。
该线程执行一个方法 (Method2
) 并在执行期间抛出异常。
我需要获取有关调用方法 (Method1
)
有什么办法可以在 Method1
中捕获 Method2
中抛出的异常吗?
最佳答案
在 .NET 4 及更高版本中,您可以使用 Task<T>
类而不是创建新线程。然后你可以使用 .Exceptions
获得异常任务对象上的属性。
有两种方法:
在一个单独的方法中://你在一些任务的线程中处理异常
class Program { static void Main(string[] args) { Task<int> task = new Task<int>(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) { Task<int> task = new Task<int>(Test); task.Start(); try { task.Wait(); } catch (AggregateException ex) { Console.WriteLine(ex); } Console.ReadLine(); } static int Test() { throw new Exception(); } }
请注意,您得到的异常是 AggregateException
.所有真正的异常都可以通过 ex.InnerExceptions
获得属性(property)。
在 .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(); } }
关于c# - 捕获在不同线程中抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5983779/