gpt4 book ai didi

c# - 将程序集加载到新的应用程序域而不是 CurrentDomain

转载 作者:太空宇宙 更新时间:2023-11-03 10:37:31 25 4
gpt4 key购买 nike

所以我的问题围绕着节省内存。

本质上,我需要将程序集加载到主域/当前域以外的单独应用程序域中,检查该程序集中的类型,然后在完成后卸载新域。

目前我的解决方案如下:

AppDomain NewDomain = AppDomain.CreateDomain("newdomain");

foreach(string path in dllPaths) //string list of dll paths
{
byte[] dllBytes = File.ReadAllBytes(dll);
NewDomain.Load(dllBytes); //offending line
}

DoStuffWithNewDomain();
AppDomain.Unload(NewDomain);

NewDomain.Load 行似乎将程序集加载到新域中,但也加载到我程序的当前域中。

我使用此链接作为引用 - http://www.csharp411.com/how-to-load-a-net-assembly-into-a-separate-appdomain-so-you-can-unload-it/

非常感谢:)

最佳答案

如前所述,从字节加载程序集只能发生在当前应用程序域中。

这是上下文切换的一种方法,可以使您的目标应用程序域成为当前应用程序域,方法是在应用程序域 (http://msdn.microsoft.com/en-us/library/system.appdomain.docallback%28v=vs.110%29.aspx) 上使用 DoCallBack 方法。

加载程序集后,您可以使用相同的方法检查新应用程序域的程序集和类型,并根据需要创建实例,然后再卸载它。

class Program
{
static void Main(string[] args)
{
AppDomain newDomain = AppDomain.CreateDomain("NewDomain");
List<string> dllPaths = new List<string>() { @"c:\dev\taglib-sharp.dll" };

foreach (string dll in dllPaths)
{
AppDomainAsmLoader asmLoad = new AppDomainAsmLoader(File.ReadAllBytes(dll));
newDomain.DoCallBack(new CrossAppDomainDelegate(asmLoad.LoadAsm));
}

newDomain.DoCallBack(new CrossAppDomainDelegate(DoWorkWithAppDomain));

AppDomain.Unload(newDomain);
Console.ReadKey();
}

public static void DoWorkWithAppDomain()
{
Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly asm in asms)
{
Type[] types = asm.GetTypes();
foreach (Type type in types)
{
Console.WriteLine("Found the type: {0}", type.FullName);
}
}
}

[Serializable]
public class AppDomainAsmLoader
{
private byte[] AsmData;

public AppDomainAsmLoader(byte[] data)
{
AsmData = data;
}

public void LoadAsm()
{
Assembly asm = Assembly.Load(AsmData);
}

}
}

关于c# - 将程序集加载到新的应用程序域而不是 CurrentDomain,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27071379/

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