How to debug/break in codedom compiled code

后端 未结 2 1767
醉话见心
醉话见心 2020-12-09 09:24

I have an application which loads up c# source files dynamically and runs them as plugins. When I am running the main application in debug mode, is it possible to debug int

相关标签:
2条回答
  • 2020-12-09 09:52

    Try the following options:

    parameters.GenerateInMemory = false; //default
    parameters.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true);
    parameters.IncludeDebugInformation = true;
    

    I am not sure if this works OK in your case, but if it does, you can surround this parameters with conditional compilation directive, so that it dumps the generated assembly only in debug mode.

    0 讨论(0)
  • 2020-12-09 09:57

    The answer by @bbmud is correct, though it misses one bug fix. The CSharpCodeGenerator (the class in .NET the compiles C# code to IL) is set to remove pdb files immediately after they are created, UNLESS you add /debug:pdbonly to the CompilerOptions string. However, if you do that, the IncludeDebugInformation flag is ignored and the compiler generates optimised code which is hard to debug. To avoid this you must explicitly tell the Code Generator to keep all files.

    Here is the complete recipe:

    parameters.GenerateInMemory = false; //default
    parameters.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true);
    parameters.IncludeDebugInformation = true;
    parameters.TempFiles.KeepFiles = true
    

    Here is the culprit part of the code of CSharpCodeGenerator:

      string fileExtension = "pdb";
        if ((options.CompilerOptions != null) && (CultureInfo.InvariantCulture.CompareInfo.IndexOf(options.CompilerOptions, "/debug:pdbonly", CompareOptions.IgnoreCase) != -1))
        {
            results.TempFiles.AddExtension(fileExtension, true);
        }
        else
        {
            results.TempFiles.AddExtension(fileExtension);
        }
    

    The TempFiles.AddExtension(fileExtension, true) tells the compile to keep the pdb files. The else option of results.TempFiles.AddExtension(fileExtension); tells it to treat pdb as all temporary files which by default means delete them.

    0 讨论(0)
提交回复
热议问题