Can I prevent an uncaught exception in another AppDomain from shutting down the application?
Asked Answered
V

2

8

I'm having trouble with a misbehaved library that throws an exception in a finalizer, which of course crashes the application.

To avoid this, I tried loading the library in its own AppDomain, but the exception still bubbles to the surface and crashes the application.

As documented on MSDN, registering to AppDomain.UnhandledException doesn't prevent the exception from bubbling up, but I'm quite surprised that there is no other way to catch such an exception in a "sub AppDomain".

How do plugin hosts, or applications that use AppDomains to sandbox potentially harmful code, do to stop unhandled exceptions ? Is it in fact possible ?

Note: I already have another workaround, the one described here. The bad finalizer is on a long-lived object, which seems to be only collected during shutdown, so it is sufficient to hide this "bogus" error from the user. Still, I find this workaround brittle, since it will either hide other, real errors, or risk blowing up my application if the object is collected earlier.

Vitus answered 11/10, 2010 at 12:44 Comment(2)
Why can't you catch the exceptionTonality
The exception is thrown in a Finalizer, which run in their own thread managed by the CLR, so I can't put an exception handler on the thread. Also, this is a library of the "legacy, unmaintaiend and important component with no source code available" kind...Vitus
S
4

An AppDomain is nice since you can ditch the program state but you still have the problem that the thread is dead. That this happens on the finalizer thread is fatal, the CLR will abort the process without recourse.

The only 'fix' is to run this component in its own process. You can shoot it in the head with Process.Kill() to prevent the finalizer thread from running at process exit. Use one of the interprocess communication mechanisms that .NET supports to talk to it. A socket, named pipe, Remoting or WCF. Good luck with it.

Sapsago answered 11/10, 2010 at 13:53 Comment(1)
Thanks for the answer, I thought there was a better isolation between AppDomains, too bad. I think we will stay with the current workaround for now, and isolate the library in its own process in the next version.Vitus
R
0

Actually, back in .NET 1.0/1.1, it behaved as you need. You can still revert to this behavior by simply adding this row to your application configuration file, inside the "runtime" node:

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

This will prevent an unhandled exception in a different thread from terminating the entire process.

Rhenium answered 12/5, 2011 at 9:52 Comment(1)
I know about this option, but that would hide exceptions from every thread, which is definitely not what I want.Vitus

© 2022 - 2024 — McMap. All rights reserved.