Catch Exceptions Thrown in a Separate Thread
In multithreaded applications, it's crucial to handle exceptions that occur in separate threads. This guide will demonstrate two approaches to accomplish this.
Task-Based Exception Handling in .NET 4 and Above
Consider using 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); }
Exception Handling in .NET 3.5
For .NET 3.5, consider the following approaches:
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);
The above is the detailed content of How to Catch Exceptions from Separate Threads in .NET?. For more information, please follow other related articles on the PHP Chinese website!