Use AppDomain to load/unload external assemblies

后端 未结 8 2059
遇见更好的自我
遇见更好的自我 2020-12-24 08:39

My scenario is as follows:

  • Create new AppDomain
  • Load some assemblies into it
  • Do some magic with loaded dlls
  • Unload AppDomain to rele
8条回答
  •  误落风尘
    2020-12-24 09:35

    Answering my own question - don't know if there's better way to do it on StackOverflow... If there is, I'd be grateful for instructions... Anyway, digging through internet I found another solution, which I hope is better. Code below, if anyone finds any weak points - please respond.

    class Program
    {
        static void Main(string[] args)
        {
            Console.ReadLine();
            for(int i=0;i<10;i++)
            {
                AppDomain appDomain = AppDomain.CreateDomain("MyTemp");
                appDomain.DoCallBack(loadAssembly);
                appDomain.DomainUnload += appDomain_DomainUnload;
    
                AppDomain.Unload(appDomain);        
            }
    
            AppDomain appDomain2 = AppDomain.CreateDomain("MyTemp2");
            appDomain2.DoCallBack(loadAssembly);
            appDomain2.DomainUnload += appDomain_DomainUnload;
    
            AppDomain.Unload(appDomain2);
    
            GC.Collect();
            GC.WaitForPendingFinalizers();  
            Console.ReadLine();
        }
    
        private static void loadAssembly()
        {
            string fullPath = @"E:\tmp\sandbox\AppDomains\AppDomains1\AppDomains1\bin\Debug\BigLib.dll";
            var assembly = Assembly.LoadFrom(fullPath);
            var instance = Activator.CreateInstance(assembly.GetTypes()[0]);
            Console.WriteLine("Creating instance of {0}", instance.GetType());
            Thread.Sleep(2000);
            instance = null;
        }
    
        private static void appDomain_DomainUnload(object sender, EventArgs e)
        {
            AppDomain ap = sender as AppDomain;
            Console.WriteLine("Unloading {0} AppDomain", ap.FriendlyName);
        }
    }
    

提交回复
热议问题