157 recommendations for writing high-quality code to improve C # programs--recommendation 66: Correctly capturing exceptions in multiple threads

Source: Internet
Author: User

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   "                );                });            T.start ();             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

157 recommendations for writing high-quality code to improve C # programs--recommendation 66: Correctly capturing exceptions in multiple threads

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.