I have a .Net 4.0 application that I need to improve the performance of code running in a partial trust environment. Specifically, I would like to eliminate the need to JIT at runtime. Normally this is accomplished using NGEN (http://http://msdn.microsoft.com/en-us/library/6t9t5wcf(v=vs.100).aspx) but this doesn't work for assemblies running in partial trust. Do I have any other options?
Native images that are generated with Ngen.exe can no longer be loaded into
applications that are running in partial trust.
What I ended up doing was performing the JIT at runtime via the PrepareMethod method. Instead of doing this inside of the untrusted application, I did it in the fully trusted portion of the app before the type was sent into the partially trusted sandbox to run. I used a mechanism similar to the one found on Liran Chen's blog here:
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);
}
}
}