Dot-Net

如何確定裝配是否已被 ngen’d?

  • May 5, 2020

您如何確定特定的 .Net 程序集是否已經被生成?我需要從程式碼中檢查。即使呼叫命令行也可以。目前我看不到任何確定這一點的方法。

您可以嘗試在“ngen 記憶體”(C:\Windows\assembly\NativeImages_v2XXXXXXX)中找到您的程序集。

Сached 程序集將具有以下格式名稱: $$ basename $$. 。$$ baseextension $$.

從程式碼檢查

檢查我們是否正在為正在執行的程序集載入本機圖像。我正在載入的模組文件名屬性中尋找模式“\assemblyname.ni”。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Diagnostics;

namespace MyTestsApp
{
   class Program
   {
       static bool Main(string[] args)
       {

           Process process = Process.GetCurrentProcess();

           ProcessModule[] modules = new ProcessModule[process.Modules.Count]; 
           process.Modules.CopyTo(modules,0);

           var niQuery = from m in modules where m.FileName.Contains("\\"+process.ProcessName+".ni") select m.FileName;
           bool ni = niQuery.Count()>0 ?true:false;

           if (ni)
           {
               Console.WriteLine("Native Image: "+niQuery.ElementAt(0));
           }
           else
          {
               Console.WriteLine("IL Image: " + process.MainModule.FileName);
          }

           return ni;
       }
   }
}

命令行解決方案:

在命令提示符下執行“ngen display”。

例子:

ngen 顯示 MyTestsApp.exe

如果安裝,它會列印出類似 Native Images: MyTestsApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

並返回 0 (%errorlevel%)

否則,它會列印出:

錯誤:未安裝指定的程序集。

並返回 -1

引用自:https://stackoverflow.com/questions/2167382