AppDomain, handling the exceptions

前端 未结 4 772
孤街浪徒
孤街浪徒 2020-12-08 22:30

I am developing a large application which consists of many smaller plugins/applications.

They are not big enough to be a full process, but are too small to be run in

4条回答
  •  长情又很酷
    2020-12-08 22:43

    Since .NET 2.0 unhandled exceptions crash the process. From AppDomain.UnhandledException event documentation:

    This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application.

    The same goes for AppDomain.FirstChanceException:

    This event is only a notification. Handling this event does not handle the exception or affect subsequent exception handling in any way.

    You need to think about how you will handle exceptions just like you will do it in normal app. Just using AppDomains will not help. If the exception has not been handled within given AppDomain it will get rethrown in calling AppDomain until it either get handled or crashes the process. It is perfectly fine to handle some exceptions and don't let them crash your process.

    AppDomain is a logical container for assemblies and memory (not for threads). Isolation for AppDomain implies:

    • Objects created in domain A can not be accessed directly by domain B (without marshaling). This allows for domain A to be unloaded without affecting anything in domain B. These objects will get automatically deleted when 'owning' domain gets unloaded.

    • Assemblies can be automatically unloaded with AppDomain. This the only way you can unload managed dll from process. This is useful for DLL hot-swapping.

    • AppDomain security permissions and configuration can be isolated from other AppDomains. This can be helpful when you load untrusted third party code. It also lets you override how assemblies will be loaded (version binding, shadow copying etc).

    Most common reasons for using AppDomain is when you run untrusted third party code. Or you have unmanaged code and want to host CLR or need dll hot swapping. I think that in CLR hosting scenario you can save your process from crashing when thirdparty code throws unhandled exception.

    Also instead of rolling your own infrastructure you might want to look at System.Addin or MEF.

提交回复
热议问题