shtse8
shtse8

Reputation: 1365

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?

Upvotes: 23

Views: 2347

Answers (2)

mes
mes

Reputation: 96

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.

Upvotes: 3

Base64__
Base64__

Reputation: 107

From what i can tell, there isn't really a native way to check if you are running in AOT. The method you described of running JIT-only methods and catching the errors would probably be the best way to go. that would probably be how the native method would do it anyway, if one existed.

Upvotes: 0

Related Questions