Recommended exception Handling in 86:parallel
Recommendation 85 illustrates how to handle exceptions in a task. Because the Start method of the task is started asynchronously, we need additional techniques to complete the exception handling. Parallel is relatively simple, because the caller line of parallel routines wait until all the tasks are complete before continuing their work. In simple terms, it has the characteristics of synchronization, so the following code can be implemented to wrap the concurrency exception into the main thread:
Static voidMain (string[] args) { Try { varParallelexceptions =NewConcurrentqueue<exception>(); Parallel.For (0,1, (i) = = { Try { Throw NewInvalidOperationException ("exceptions that occur in parallel tasks"); } Catch(Exception e) {parallelexceptions.enqueue (e); } if(Parallelexceptions.count >0) Throw Newaggregateexception (parallelexceptions); }); } Catch(aggregateexception err) {foreach(Exception IteminchErr. InnerExceptions) {Console.WriteLine ("Exception type: {0}{1} from:{2}{3} Exception Content: {4}", item. Innerexception.gettype (),Environment.NewLine, item. Innerexception.source, Environment.NewLine, item. Innerexception.message); }} Console.WriteLine ("The main thread ends immediately"); Console.readkey (); }
The output of this piece of code is:
Exception type: System.InvalidOperationException
From: ConsoleApplication2
Exception content: Exceptions that occur in parallel tasks
The main thread ends immediately
In parallel exception handling, we used a thread-safe generic collection concurrentqueue<t> to handle the collection thread security issues that might be encountered in concurrency (see recommendation 22: Ensure thread safety for collections).
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--Recommendations for exception handling in 86:parallel