.net 4.0 部分信任应用的NGen

.net 4.0 部分信任应用的NGen,.net-4.0,jit,ngen,partial-trust,.net 4.0,Jit,Ngen,Partial Trust,我有一个.NET4.0应用程序,我需要它来提高在部分信任环境中运行的代码的性能。具体来说,我想消除在运行时进行JIT的需要。通常,这是使用NGEN()完成的,但这不适用于在部分信任中运行的程序集。我还有其他选择吗 Native images that are generated with Ngen.exe can no longer be loaded into applications that are running in partial trust. 我最终做的是通过该方法在运行时执

我有一个.NET4.0应用程序,我需要它来提高在部分信任环境中运行的代码的性能。具体来说,我想消除在运行时进行JIT的需要。通常,这是使用NGEN()完成的,但这不适用于在部分信任中运行的程序集。我还有其他选择吗

Native images that are generated with Ngen.exe can no longer be loaded into 
applications that are running in partial trust. 

我最终做的是通过该方法在运行时执行JIT。我没有在不受信任的应用程序中执行此操作,而是在将类型发送到部分受信任的沙盒中运行之前,在应用程序的完全受信任部分执行此操作。我使用了一种类似于陈丽然博客上的机制:

public static void PreJITMethods(Assembly assembly)
{
    Type[] types = assembly.GetTypes();
    foreach (Type curType in types)
    {
        MethodInfo[] methods = curType.GetMethods(
            BindingFlags.DeclaredOnly |
            BindingFlags.NonPublic |
            BindingFlags.Public |
            BindingFlags.Instance |
            BindingFlags.Static);

        foreach (MethodInfo curMethod in methods)
        {
            if (curMethod.IsAbstract || curMethod.ContainsGenericParameters)
                continue;

            RuntimeHelpers.PrepareMethod(curMethod.MethodHandle);
        }
    }
}