How to properly unload an AppDomain using C#?

后端 未结 2 1990
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-16 10:55

I have an application that loads external assemblies which I have no control over (similar to a plugin model where other people create and develop assemblies that are used b

相关标签:
2条回答
  • 2020-12-16 11:33

    I've dealt with a similar problem in my app. Basically, you can't do anything more to force the AppDomain to go down than Unload does.

    It basically calls abort of all threads that are executing code in the AppDomain, and if that code is stuck in a finalizer or unmanaged code, there isn't much that can be done.

    If, based on the program in question, it's likely that the finalizer/unmanaged code will finish some later time, you can absolutely call Unload again. If not, you can either leak the domain on purpose or cycle the process.

    0 讨论(0)
  • 2020-12-16 11:50

    Try to make GC.Collect() if you do not unload the domain.

     try
        {
           AppDomain.Unload(otherAssemblyDomain);
        }
        catch (CannotUnloadAppDomainException)
        {
           GC.Collect();
           AppDomain.Unload(otherAssemblyDomain);
        }
    
    0 讨论(0)
提交回复
热议问题