gpt4 book ai didi

c# - 从应用程序域卸载程序集

转载 作者:行者123 更新时间:2023-12-01 18:03:11 29 4
gpt4 key购买 nike

代码应该创建域,将 dll 加载到域中,卸载 dll

但是在新域上调用 unload 后 dll 仍然存在吗?

 private void Method1()
{
//create new domain
AppDomain domain = AppDomain.CreateDomain("MyDomain");
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

//load dll into new domain
AssemblyName assemblyName = new AssemblyName();
assemblyName.CodeBase = "c:\\mycode.dll";
Assembly assembly = domain.Load(assemblyName);

//do work with dll
//...

//unload dll
AppDomain.Unload(domain);

//still showing dll below ?????
Assembly[] aAssemblies = AppDomain.CurrentDomain.GetAssemblies();
}
static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string[] tokens = args.Name.Split(",".ToCharArray());
System.Diagnostics.Debug.WriteLine("Resolving : " + args.Name);
return Assembly.LoadFile(Path.Combine(new string[] { "c:\\", tokens[0] + ".dll" }));
}

有什么想法为什么 dll 没有卸载吗?

编辑(让它按如下方式工作)

正如 Jean 指出的那样,domain.Load 是问题所在,在同一项目中使用带有代理类的 CreateInstanceAndUnwrap 是可行的。)

而不是

    //load dll into new domain *** this does not work
AssemblyName assemblyName = new AssemblyName();
assemblyName.CodeBase = "c:\\mycode.dll";
Assembly assembly = domain.Load(assemblyName);

到此

    // loads proxy class into new domain               
Type myType = typeof(Proxy);
var value = (Proxy)domain.CreateInstanceAndUnwrap(
myType.Assembly.FullName,
myType.FullName);
//DoWork:- loads assembly into domain
// calls methods, returns result
Int32 result = value.DoWork(pathToDll);
//Unload domain and thus assembly
AppDomain.Unload(domain);
//Assembly not present in current domain
Assembly[] list = AppDomain.CurrentDomain.GetAssemblies();

将以下类添加到当前命名空间

    public class Proxy : MarshalByRefObject
{
public Int32 DoWork(string assemblyPath)
{
try
{
Assembly assembly = Assembly.LoadFile(assemblyPath);
Int32 response = 0;

Type tObject = assembly.GetType("namespace.class");
MethodInfo Method = tObject.GetMethod("method");

Type myType = typeof(Proxy);
object myInstance = Activator.CreateInstance(myType);
response = (Int32) Method.Invoke(myInstance, null);

return response;
}
catch (Exception ex)
{
throw ex;
}
}
}

最佳答案

根据经验,一旦有了 Assembly 实例,就意味着相关程序集已加载到当前域中。

这意味着,当您调用AppDomain.Load时方法,您可以在当前域和新域中加载程序集。 (正如您在 MSDN 上对该方法的注释中看到的那样,“此方法只能用于将程序集加载到当前应用程序域中。”)

编辑:之前发布的“解决方案”已被删除,因为它并没有真正解决问题。作者将可行的解决方案编辑到问题中。

关于c# - 从应用程序域卸载程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20230634/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com