Various types of anomaly capture

Source: Internet
Author: User

One, UI thread exception:

1) directly in the main thread of the exception, directly with Try......catch capture (if you suspect that a code will throw an exception).

2) Other possibilities: it is recommended to use Application.threadexception+application.setunhandledexception to catch exceptions and to prevent application termination.

1  Private void button1_click (object  sender, EventArgs e)2        {3             thrownew Exception ("UI Exception thrown "); 4         }

In the Program.cs entry function:

 Public classProgram {/// <summary>        ///The main entry point for the application. /// </summary>[STAThread]Static voidMain () {application.threadexception+=application_threadexception;            Application.setunhandledexceptionmode (unhandledexceptionmode.catchexception);            Application.enablevisualstyles (); Application.setcompatibletextrenderingdefault (false); Form1 F1=NewForm1 ();        Application.Run (F1); }        Private Static voidApplication_threadexception (Objectsender, Threadexceptioneventargs e) {            using(varf = File.appendtext ("C:\\error2.txt") {f.writeline (e.exception.message); }        }    }

Clicking the button throws an exception (UI exception).

Second, task exception capture:

1) Use wait capture (because wait places the task exception into the main thread, so the main thread can capture it).

Note that the exception caught with wait is not exception but aggregateexception, where you get innerexceptions, using the exception traversal of foreach:

 Try{Task.Factory.StartNew ()=                   {                       Throw NewException ("manually created thread exceptions"); }).            Wait (); }            Catch(AggregateException ex) {foreach(varIteminchEx. Flatten (). InnerExceptions) {//to deal with your anomalies here.                }            }

2) processing within task (recommended)

Task.Factory.StartNew (() =                   {                      try                        {                        }                      catch  ( Exception e)                         {                         }                   }). Wait ();

3) Use the Continue method to process:

Task.Factory.StartNew (() =            {                thrownew Exception (" manually created thread exception ");             = = T.exception.flatten () ...);

4) When using await (asynchronous), directly in the GUI thread try......catch ... Catch exceptions (like normal code, what exceptions catch what exceptions).

5) All task exceptions (not using await or wait, pure multithreaded exceptions, internal not processed) cannot be captured by the main thread, and should be in WinForm (console console in main entry function), Using taskschedule.unobservedtaskexception:

namespacecsharpwinform{ Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); Taskscheduler.unobservedtaskexception+=taskscheduler_unobservedtaskexception; }        Private voidTaskscheduler_unobservedtaskexception (Objectsender, Unobservedtaskexceptioneventargs e) {            using(varf = File.appendtext ("C:\\error.txt"))            {                foreach(varIteminchE.exception.flatten (). InnerExceptions) {F.writeline ("Task Exception:"+item.                Message);        }} e.setobserved (); }        Private voidButton1_Click (Objectsender, EventArgs e) {Task.Factory.StartNew ()=            {                Throw NewException ("manually created thread exceptions");            }); Gc.            Collect (); Gc.        WaitForPendingFinalizers (); }    }}

Note: Because the unobservedtaskexception must not be displayed until after the garbage is reclaimed to finalize, it is not necessarily captured every time. To improve accuracy, the GC method must be used.

Various types of anomaly capture

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.