问题
It seems the .NET AppDomain.AssemblyLoad
event catches any exceptions thrown within it's event handlers, not propagating them to the caller who triggered the assembly load (e.g. Assembly.LoadFile()
).
My first question is why does this catch all exceptions behavior exist? Microsoft are generally pretty strict about ensuring exceptions always propagate in their BCLs.
My second question, is there any way to turn off this behavior?
Background: I need to scan assemblies as they are loaded and ensure they comply with some convention. If they don't, an exception should be thrown (and caught higher up by multiple mechanisms that could trigger the assembly load).
Note: I already found this question 'Throw exception from AppDomain.AssemblyLoad event', which is not a duplicate. My question logically follows from the conclusion of that question.
回答1:
No, exceptions are swallowed inside the CLR, no way to alter that behavior. This is the case for most of the AppDomain events: AssemblyLoad, DomainUnload and ProcessExit. The SSCLI20 source code has no comments that indicate why this is done.
A rough guess is that the code is buried too deep inside CLR stack frames to allow a reasonable diagnostic and unwinding frames and restoring state is too difficult. AssemblyLoad because that event is almost always raised while the jitter is busy generating code, DomainUnload and ProcessExit because the CLR is busy shutting down all code execution.
The workaround is clear, if you must catch exceptions then you need a try/catch statement in your event handler.
来源:https://stackoverflow.com/questions/12529025/appdomain-assemblyload-event-catches-all-exceptions-raised-within-the-event-hand