UI in exception handler

Topics: Exception Handling Application Block
Aug 10, 2010 at 10:38 PM
Trying to use a WinForm or WPF window in an exception handler will potentially fail if the exception occurs on a non-STA thread. All the examples of notifying the user I've seen use the standard MessageBox but, let's face it, MB is horribly outdated. So I created a custom error dialog that I want displayed when an unhandled exception occurs. Unfortunately we have no control over the thread the exception is handled on. So how can you display a UI in a handler without running into this problem? I can think of a couple of solutions. The first solution is to dispatch the request to the synchronization context but this seems like a dangerous process. If the exception occurred while in the sync context then it seems like it might result in a cascading set of failures or, perhaps, a deadlock. The alternative solution is to spawn an STA thread that displays the dialog and then goes away. This seems like a safer solution but seems more complicated than it should be. Has anyone solved this problem and/or have a better solution?
Aug 11, 2010 at 4:06 AM

Your problems seems more of multi-threading issues and not on creating the custom exception handler.  I suggest you post it in other .NET forums as I'm not an expert on multi-threading.


Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.

Aug 11, 2010 at 2:24 PM

That's not necessarily true.  It is a threading apartment problem in general.  UIs (WinForms and WPF) require that the thread upon which you display a window to be an STA.  Whether you have 1 or 20 threads is irrelevant.  STA must be set early in the thread's life otherwise it'll default to MTA making the thread useless for displaying UIs.  Hence you either have to be running on an existing UI thread, create your own STA thread or marshal to a UI thread.  

I outlined the solutions that came to my mind but was hoping others have already solved the solution.  Currently I'm opting for the spawning of a temporary STA thread but it isn't ideally.  My preferred solution would be to have the EAB allow handlers to expose their threading requirements (on UI thread, on STA, from same thread that created handler, etc) and the EAB would manage ensuring the handler was called properly.  Right now EAB just calls each handler in turn on the (presumably) unhandled exception's thread.