Recommendation 66: Correctly capture exceptions in multiple threads
Multi-threaded exception handling requires a special approach. There is a problem with this approach:
try {Thread T = new Thread ((threadstart) delegate throw new Exception ( " multithreading exception " catch (Exception error) { MessageBox.Show (Error. Message + environment.newline + error. StackTrace); }
The application does not capture the thread's exception here, but it exits directly. Starting with. NET2.0, an unhandled exception on any thread will cause the application to exit (triggering the AppDomain's unhandledexception first). The Try-catch in the code above actually captures the current thread's exception, and T is the new exception, so the correct approach is:
Thread T =NewThread ((ThreadStart)Delegate { Try { Throw NewException ("Multithreading Exceptions"); } Catch(Exception error) {MessageBox.Show ("worker thread Exception:"+ error. Message + Environment.NewLine +error. StackTrace); } }); T.start ();
That is, the catch of the exception in the new thread allows all the thread's internal code to try up. In principle, the business exception for each thread should be handled within itself, but we still need a way to pass an exception inside the thread to the main path.
In a Windows Forms program, you can use the form's BeginInvoke method to pass an exception to the main form thread:
Thread T =NewThread ((ThreadStart)Delegate { Try { Throw NewException ("Non-form thread exception"); } Catch(Exception ex) { This. BeginInvoke (Action)Delegate { Throwex; }); } }); T.start ();
The above code will eventually trigger the application.threadexception of the main thread.
In a WPF form, you can do this:
Thread T =NewThread ((ThreadStart)Delegate { Try { Throw NewException ("Non-form thread exception"); } Catch(Exception ex) { This. Dispatcher.invoke (Action)Delegate { Throwex; }); } }); T.start ();
However, in addition to the two methods above, we recommend using event callbacks to wrap the worker thread's exception to the main thread. The benefit of handling exceptions in the form of event callbacks is to provide a uniform entry for exception handling. This approach will be elaborated in recommendation 85.
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
"Go" writing high-quality Code 157 recommendations for improving C # programs--recommendation 66: Correctly capturing exceptions in multiple threads