Equivalent to System.Windows.Forms.Application.ThreadException for a console application or Windows service or any process in general

In WinForms, I use:

  • System.Windows.Forms.Application.ThreadException
  • System.Windows.Application.UnhandledException

What should I use for a multi-threaded application without Winforms?

Consider the full code below in C # .NET 4.0:

using System; using System.Threading.Tasks; namespace ExceptionFun { class Program { static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Task.Factory.StartNew(() => { throw new Exception("Oops, someone forgot to add a try/catch block"); }); } static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { //never executed Console.WriteLine("Logging fatal error"); } } } 

I saw many similar questions in stackoverflow, but none of them contained a satisfactory answer. Most answers are of the type: "You must include the correct exeption handling in your code" or "Use AppDomain.CurrentDomain.UnhandledException".

Edit: it looks like my question was misinterpreted, so I reformulated it and presented an example of smaller code.

+6
source share
1 answer

You don't need any equivalents, the CurrentDomain.UnhandledException event CurrentDomain.UnhandledException fine in multi-threaded console applications. But this is not shooting in your case because of how you start your thread. The handler in your question will not run on both Windows and console applications. But if you start your thread like this (for example):

 new Thread(() => { throw new Exception("Oops, someone forgot to add a try/catch block"); }).Start(); 

He will light up.

The problem Task.Factory.StartNew(...) and CurrentDomain.UnhandledException fixed in many posts on SO. Check out some suggestions here:

How to handle all unhandled exceptions when using a parallel task library?

What is the best way to catch an exception in a Task?

0
source

Source: https://habr.com/ru/post/920110/


All Articles