Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround for async event handler of AppDomain.CurrentDomain.UnhandledException

Tags:

c#

I want to create a bug report in an issue tracker system when an unhandled exception occures. Since this is done by a series of async http requests, the corresponding method is async returning a task:

AppDomain.CurrentDomain.UnhandledException += async (sender,eventArgs) => 
    await CreateBugReport(eventArgs.ExceptionObject);

Unfortunately this does not work, since the message loop terminates before all http requests are done and the CreateBugReport method is not completed.

The alternative

AppDomain.CurrentDomain.UnhandledException += (sender,eventArgs) => 
    CreateBugReport(eventArgs.ExceptionObject).Wait();

does not work either, it rather hangs forever (which is expected behaviour).

Another constraints is that the method CreateBugReport opens a dialog for querying additional information, so it should probably be executed in the UI thread.

What is the best workaround for this issue?

like image 328
MarkusParker Avatar asked Oct 14 '25 03:10

MarkusParker


1 Answers

From the comments it seems that your CreateBugReport is going to show UI to the user. Yet, Wait hangs due to deadlock and Task.Run does not work because there's no UI thread there.

Create a second UI thread just for that dialog (a LongRunning task should work. Call Application.Run on that new thread again as if it was your Main method.). You can then delay the UnhandledException handler until that second thread is done.

Hans Passant says in the comments that this is a bit unsafe and I agree. But it might be an easy and pragmatic solution that just works in practice. If the code which creates the bug report is not sharing data with the code that crashed I don't see why it would not work. The crashed code remains frozen (and it's UI frozen as well).

You also could write the error details to a temp file, relaunch the application and on application start process any such temp files.

like image 184
usr Avatar answered Oct 19 '25 19:10

usr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!