解决.NET Runtime Optimization Service占用大量CPU

今天在给一台服务器(windows server 2012 R2)更新系统之后发现有一个名为.NET Runtime Optimization Service的进程占用了大量的CPU,手动进程也结束不掉,具体进程如下图:

经查询发现更新中包含了.net Framework,触发了.NET的最佳化服务,这个最佳化服务在你安装完.NET之后还会继续预编译那些高优先级的assemblies,然后等到你的电脑空闲的时候再去处理那些低优先级的assemblies,一但处理完毕会自动结束,但是我们不知道他会什么时候处理完毕,而一直占用服务器CPU会导致部署的应用访问速度变慢,我们可以利用以下脚本加速这项服务完成处理。

# Script to force the .NET Framework optimization service to run at maximum speed.

$isWin8Plus = [Environment]::OSVersion.Version -ge (new-object 'Version' 6,2)
$dotnetDir = [environment]::GetEnvironmentVariable("windir","Machine") + "\Microsoft.NET\Framework"
$dotnet2 = "v2.0.50727"
$dotnet4 = "v4.0.30319"

$dotnetVersion = if (Test-Path ($dotnetDir + "\" + $dotnet4 + "\ngen.exe")) {$dotnet4} else {$dotnet2}

$ngen32 = $dotnetDir + "\" + $dotnetVersion +"\ngen.exe"
$ngen64 = $dotnetDir + "64\" + $dotnetVersion +"\ngen.exe"
$ngenArgs = " executeQueuedItems"
$is64Bit = Test-Path $ngen64


#32-bit NGEN -- appropriate for 32-bit and 64-bit machines
Write-Host("Requesting 32-bit NGEN") 
Start-Process -wait $ngen32 -ArgumentList $ngenArgs

#64-bit NGEN -- appropriate for 64-bit machines

if ($is64Bit) {
    Write-Host("Requesting 64-bit NGEN") 
    Start-Process -wait $ngen64 -ArgumentList $ngenArgs
}

#AutoNGEN for Windows 8+ machines

if ($isWin8Plus) {
    Write-Host("Requesting 32-bit AutoNGEN -- Windows 8+") 
    schTasks /run /Tn "\Microsoft\Windows\.NET Framework\.NET Framework NGEN v4.0.30319"
}

#64-bit AutoNGEN for Windows 8+ machines

if ($isWin8Plus -and $is64Bit) {
    Write-Host("Requesting 64-bit AutoNGEN -- Windows 8+") 
    schTasks /run /Tn "\Microsoft\Windows\.NET Framework\.NET Framework NGEN v4.0.30319 64"
}

把上述代码保存为ps1文件,然后右键选择PowerShell运行,等脚本运行完毕.NET Runtime Optimization Service进程就会消失,Cpu占用也会结束。

参考文章:CSDN博主:咖啡那么浓

THE END