Search code examples
c#ahead-of-time-compile

How to check the code is running in AOT in C#?


I am using compiled expressions to create instance. It is very fast in JIT but not in AOT (even slower) because of the fallback process. So I want to check whether the code is running in AOT. If yes, I will use ConstructorInfo.Invoke instead.

ATM, I only have an idea to check this by calling one of the methods are not allowed in AOT and then catch the error. Does any other better ways to check?


Solution

  • Does the System.Runtime.CompilerSerivces.RuntimeFeatures class, with its IsDynamicCodeCompiled and IsDynamicCodeSupported properties, meet the need? It is available in more recent versions of .NET.

    • .NET Core 2.0+
    • .NET Framework 4.7.1+
    • .NET Standard 2.1

     

    From the .NET Standard 2.1 Announcement:

    We also exposed two new capability APIs that allow you to check for the ability to generate code at all (RuntimeFeature.IsDynamicCodeSupported) as well as whether the generated code is interpreted or compiled (RuntimeFeature.IsDynamicCodeCompiled). This will make it much easier to write libraries that can exploit these capabilities in a portable fashion.

    In looking at the .NET source code for Regex, this perhaps might be the check that is triggering the fallback process that was noted, in which case you could then potentially check IsDynamicCodeCompiled yourself and provide your alternate fallback.