1

Is it possible to catch unexpected errors globally in c# WPF application - c# 4.0

I found that DispatcherUnhandledException was able to catch UI thread errors but actually i need TPL threads. UnhandledException was able to catch thread errors but it was still causing software to terminate.

So any solution to catch unhandled exceptions in the threads not in UI thread and still let software to run not terminate. Threads are TPL threads. (Task Parallel Library)

1

2 Answers 2

2

A part from handling DispatcherUnhandledException which you already have done add this to your config file

<configuration> <runtime> <legacyUnhandledExceptionPolicy enabled="1"/> </runtime> </configuration> 

This prevents your secondary threads exception from shutting down the application.

Sign up to request clarification or add additional context in comments.

5 Comments

so i can use this and UnhandledException to catch errors and let software continue am i correct ? but where do i put it ? it is wpf not asp.net
In your app.config file which not only exists in ASP.Net apps. It will only allow you not quit app in case of an exception. I am not sure how how will you catch them
where is this config file i don't see anywhere. i have app.xaml but it gives error when i put it there
Right click on your project -> add new item-> application configuration file
thanks. i also add this and i think both will solve problem. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyExceptionHandler);
1

You can use Custom Escalation Policy in TPL to address your case.You do this by adding an event handler to the static System.Threading.Tasks.TaskScheduler.UnobservedTaskException member

 class Test { static void Main(string[] args) { // create the new escalation policy TaskScheduler.UnobservedTaskException += (object sender, UnobservedTaskExceptionEventArgs eventArgs) => { // mark the exception as being handled eventArgs.SetObserved(); // get the aggregate exception and process the contents ((AggregateException)eventArgs.Exception).Handle(ex => { // write the type of the exception to the console Console.WriteLine("Exception type: {0}", ex.GetType()); return true; }); }; // create tasks that will throw an exception Task task1 = new Task(() => { throw new NullReferenceException(); }); Task task2 = new Task(() => { throw new ArgumentOutOfRangeException(); }); // start the tasks task1.Start(); task2.Start(); // wait for the tasks to complete - but do so // without calling any of the trigger members // so that the exceptions remain unhandled while (!task1.IsCompleted || !task2.IsCompleted) { Thread.Sleep(500); } // wait for input before exiting Console.WriteLine("Press enter to finish and finalize tasks"); Console.ReadLine(); } } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.