How to Handle Exceptions Thrown in Separate Threads
In multi-threaded applications, it becomes crucial to handle exceptions that occur in threads other than the one executing the main code. This challenge requires careful handling to ensure proper error handling and application stability.
Using Task
Since .NET 4, the Task
task.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted); private void ExceptionHandler(Task<int> task) { var exception = task.Exception; Console.WriteLine(exception); }
try { task.Wait(); } catch (AggregateException ex) { Console.WriteLine(ex); }
Using Threads in .NET 3.5
In .NET 3.5, where Task
Exception exception = null; Thread thread = new Thread(() => SafeExecute(() => Test(0, 0), Handler)); thread.Start(); private void Handler(Exception exception) { Console.WriteLine(exception); }
Exception exception = null; Thread thread = new Thread(() => SafeExecute(() => Test(0, 0), out exception)); thread.Start(); ... Console.WriteLine(exception);
By implementing these techniques, you can effectively handle exceptions thrown in different threads, ensuring that your application continues to operate reliably even in the presence of unexpected errors.
The above is the detailed content of How to Effectively Handle Exceptions from Separate Threads in .NET?. For more information, please follow other related articles on the PHP Chinese website!