AssemblyLoadContext是否隔离静态变量?
创始人
2024-09-20 14:30:30
0

AssemblyLoadContext类本身不会隔离静态变量。静态变量是在程序域级别上进行管理的,而AssemblyLoadContext只负责加载和卸载程序集。

如果需要实现静态变量在不同的程序集加载上下文中的隔离,可以通过创建自定义的程序域来实现。下面是一个示例代码:

using System;
using System.Reflection;

public class CustomAssemblyLoadContext : AssemblyLoadContext
{
    private AssemblyDependencyResolver _resolver;

    public CustomAssemblyLoadContext(string mainAssemblyPath) : base(isCollectible: true)
    {
        _resolver = new AssemblyDependencyResolver(mainAssemblyPath);
    }

    protected override Assembly Load(AssemblyName assemblyName)
    {
        string assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName);
        if (assemblyPath != null)
        {
            return LoadFromAssemblyPath(assemblyPath);
        }

        return null;
    }

    public void UnloadAllAssemblies()
    {
        foreach (Assembly assembly in GetLoadedAssemblies())
        {
            Unload(assembly);
        }
    }
}

public static class MyStaticClass
{
    public static string MyStaticVariable = "Hello, World!";
}

public class Program
{
    public static void Main(string[] args)
    {
        string mainAssemblyPath = Assembly.GetEntryAssembly().Location;

        CustomAssemblyLoadContext context1 = new CustomAssemblyLoadContext(mainAssemblyPath);
        Assembly assembly1 = context1.LoadFromAssemblyPath(mainAssemblyPath);

        // 在这个上下文中使用静态变量
        Console.WriteLine(MyStaticClass.MyStaticVariable);

        context1.UnloadAllAssemblies();

        CustomAssemblyLoadContext context2 = new CustomAssemblyLoadContext(mainAssemblyPath);
        Assembly assembly2 = context2.LoadFromAssemblyPath(mainAssemblyPath);

        // 在另一个上下文中使用静态变量
        Console.WriteLine(MyStaticClass.MyStaticVariable);

        context2.UnloadAllAssemblies();

        Console.ReadLine();
    }
}

在这个示例中,我们创建了一个自定义的AssemblyLoadContext类CustomAssemblyLoadContext。在Load方法中,我们使用AssemblyDependencyResolver来解析程序集的依赖项并加载程序集。在Main方法中,我们创建了两个不同的CustomAssemblyLoadContext实例,每个实例都加载了相同的主程序集。我们可以看到,每个上下文中的静态变量MyStaticVariable都是独立的,并且在上下文切换时保持不变。

相关内容

热门资讯

普及透视!pokemmo脚本最... 普及透视!pokemmo脚本最新版!总是一直总是有辅助工具(有挂规律)-哔哩哔哩1、玩家可以在pok...
关于透视!pokemmo修改器... 关于透视!pokemmo修改器手机版!竟然真的有辅助技巧(真实有挂)-哔哩哔哩1.pokemmo修改...
详情透视!红龙poker有辅助... 详情透视!红龙poker有辅助吗!其实有辅助技巧(有挂方式)-哔哩哔哩运红龙poker有辅助吗辅助工...
详细透视!epoker透视!一... 详细透视!epoker透视!一直有辅助工具(有挂技术)-哔哩哔哩1、epoker透视透视辅助软件激活...
辅助透视!pokemmo辅助官... 辅助透视!pokemmo辅助官网!其实一直总是有辅助工具(有挂攻略)-哔哩哔哩1、实时pokemmo...
详细透视!约局吧怎么看有没有挂... 详细透视!约局吧怎么看有没有挂!确实是真的有辅助软件(有挂秘籍)-哔哩哔哩1、游戏颠覆性的策略玩法,...
揭幕透视!红龙poker辅助平... 揭幕透视!红龙poker辅助平台!都是真的有辅助神器(讲解有挂)-哔哩哔哩进入游戏-大厅左侧-新手福...
关于透视!xpoker辅助助手... 关于透视!xpoker辅助助手!真是有辅助脚本(真的有挂)-哔哩哔哩1、超多福利:超高返利,海量正版...
科普透视!uupoker有透视... 科普透视!uupoker有透视吗!竟然一直都是有辅助插件(真是有挂)-哔哩哔哩1、完成uupoker...
解迷透视!cloudpoker... 解迷透视!cloudpoker怎么开挂!原来一直都是有辅助技巧(存在有挂)-哔哩哔哩1、解迷透视!c...