Debugging Optimized Code in .NET


Sometime back I found myself trying to remotely debug a program thru visual studio, and while trying to access the value of one of the variables I got a message saying "Cannot evaluate expression because the code of the current method is optimized"... turns out that there are compilation flags that instruct the JIT to optimize the code (usually on release builds) and thus some variables will not be available during debugging.  You may instruct the JIT not to optimize the code by doing the following:

Let's say that you have:

  • DLLYouWantToDebug.dll
  • DLLYouWantToDebug.pdb

 Then you will create a new text file with the same name as the dll you are trying to debug but with "ini" extension, example:

  • DLLYouWantToDebug.ini

Open this file with Notepad and insert the following text in it:

[.NET Framework Debugging Control]
GenerateTrackingInfo=1
AllowOptimize=0

 

This will override the optimization flag and then you will be able to see all the variable values

 

Disclaimer!

Please note that this is not intended for production usage!

 

References

http://msdn.microsoft.com/en-us/library/9dd8z24x(v=vs.110).aspx

 

The following PowerShell will disable the optimization for the files in a folder or a specific dll/exe.

Function Set-OptimizationConfigurationFiles
{
param (
[parameter(Mandatory = $true)][ValidateScript ({Test-Path $_})][string] $PathToDeploymentFolder,
[parameter(Mandatory = $false)][string] $SpecificDll)

$allDllFiles = Get-ChildItem -Path $pathToDeploymentFolder | Where-Object {($_.Name -like '*.dll' -or $_.Name -like '*.exe') -and ($SpecificDll -eq $null -or $_.Name -eq $SpecificDll)}

foreach($currentDllFile in $allDllFiles)
{
$fileName = $currentDllFile.BaseName
$iniFullFileName = $currentDllFile.DirectoryName + '\' + $fileName + '.ini'

'[.NET Framework Debugging Control]' > $inifullFileName
'GenerateTrackingInfo=1' >> $inifullFileName
'AllowOptimize=0' >> $inifullFileName
}
}

 

 

 

Comments (0)

Skip to main content