AppDomain UnhandledException

房东的猫 提交于 2020-01-03 08:48:08

问题


I am working on a C# project and want to make use of the UnhandledException event to catch any exceptions I may have missed in my project (hoping there won't be any but to be on the same side).

I make quite a bit of software so I want to make a class library that all of my projects will make use of so I want to have one function that does all of the initialisation stuff of all my projects without me having to copy and paste the code into each project to do the same work.

What I am wondering is if I have in the class library the unhandled exception event using the following code

AppDomain currentDomain = AppDomain.CurrentDomain;
            currentDomain.UnhandledException += new UnhandledExceptionEventHandler(currentDomain_UnhandledException);

Will the unhandled exception only be used from within the class library or will this event handle also be exeucted from any projects that the references the class library.

Thanks for any help you can provide.


回答1:


Assuming that all of your projects are running in the same appdomain, this will work correctly. We have this exact code encapsulated in a common DLL that is shared among numerous applications.

An additional suggestion: if this is used in Windows Forms applications, you probably also want to add a handler for System.Windows.Forms.Application.ThreadException. This serves as a backstop when, for example, someone forgets to add exception handling to a control event.




回答2:


It is possible to load an assembly into a different application domain, but as long as you load the assemblies (like class libraries) into the current application domain this will handle the exception.

Relationship between application domains and assemblies:

http://technet.microsoft.com/en-us/subscriptions/index/43wc4hhs(v=vs.80).aspx

For instance, Assembly.LoadFile() or Assembly.Load() will load the assembly into the current app domain.

Your code could be creating a new app domain with:

AppDomain.CreateDomain(..) , then it could load assemblies into this domain, which would not be handled by your code.

If you reference libraries in your project they will be loaded into the current app domain.



来源:https://stackoverflow.com/questions/14167746/appdomain-unhandledexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!