【问题标题】:Does DynamicMethod 'skipVisibility' have a performance penalty?DynamicMethod 'skipVisibility' 是否有性能损失?
【发布时间】:2018-04-23 01:53:18
【问题描述】:

当在 C# 中创建 DynamicMethod 时,绕过可见性是不必要或不相关的,为 skipVisibility 指定的最佳值是什么strong> DynamicMethod 构造函数的参数?为 skipVisibility 指定 true 是否存在性能损失,即与运行时安全需求相关联,如果是这样,每次调用都会发生这种损失,还是只在 JIT 时间,在首次访问之前进行一次?

MSDN 文档:DynamicMethod

【问题讨论】:

  • 你试过测量吗?
  • 如果没有人回答我确实会,但我推迟了,因为我不知道如何验证幕后发生了什么样的安全需求。换句话说,当您应该尝试测量的因素被运行时/JIT 完全隐藏时,很难尝试解释结果。
  • 为什么指定 skipVisibility 会有性能损失?我认为“跳过”某些东西应该会产生更好的性能。
  • @IllidanS4 是的,准确地说;我问是因为这似乎是一个奇怪的案例。由于在这种情况下“跳过”的是执行(例如)privateprotectedinternal 类声明,我相信这样做可能需要调用者在某个级别上运行提高安全性(?),并在运行时检查这是根据当前安全证据授权的,而不是简单地观察那些不需要提升(?)的声明。

标签: c# cil emit dynamicmethod dynamic-method


【解决方案1】:

我在DynamicMethod.NET 参考源中找到了一些相关代码。如下所示,指定skipVisibility 会强制要求ReflectionPermission 的安全性。 (代码还有另一种情况,无论skipVisibility 参数如何,都需要此权限。

[SecurityCritical]
private void PerformSecurityCheck(Type owner, ref StackCrawlMark stackMark, bool skipVisibility)
{
    if (owner == null)
        throw new ArgumentNullException("owner");

    RuntimeType underlyingSystemType = owner as RuntimeType;
    if (underlyingSystemType == null)
        underlyingSystemType = owner.UnderlyingSystemType as RuntimeType;

    if (underlyingSystemType == null)
        throw new ArgumentNullException("owner", Environment.GetResourceString("Argument_MustBeRuntimeType"));

    RuntimeType callerType = RuntimeMethodHandle.GetCallerType(ref stackMark);
    if (skipVisibility)
        new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
    else if (callerType != underlyingSystemType)
        new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();

    this.m_creatorAssembly = callerType.GetRuntimeAssembly();
    if (underlyingSystemType.Assembly != this.m_creatorAssembly)
        CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence, owner.Assembly.PermissionSet);
}

所以答案是当为skipVisibility 指定true 时可能会降低性能。但是,根据您与 new DynamicMethod(...) 一起使用的各种其他参数类型以及您发出的 IL,您的 DynamicMethod 实际上可能需要 ReflectionPermission,并且您将无法指定 假。在这种情况下给出的错误是:

System.TypeAccessException尝试通过安全透明方法“DynamicClass.foo(MyType,int)”访问安全关键类型“MyType”失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    相关资源
    最近更新 更多