无法使用VS Debugger Interop执行语句

And*_*ren 15 c# debugging envdte visual-studio-extensions visual-studio-2013

我正在编写一个调试器扩展VSPackage,我想在遇到断点时在调试过程中执行一个语句.在我的扩展代码中,我有这个:

void Initialize()
{
    // ...standard vspackage init code omitted...

    Globals.Init((DTE2)GetService(typeof(DTE)));              
    Globals.DebuggerEvents.OnEnterBreakMode += (dbgEventReason reason, ref dbgExecutionAction action) =>
    {
        try
        {
           var e1 = Globals.Application.Debugger.GetExpression("1+2");
           Debug.WriteLine(e1.Value);     // Prints "3"

           Globals.Application.Debugger.ExecuteStatement("x = 1+2", 1000);
           Debug.WriteLine("OK");         // Never prints this                          
        } 
        catch (Exception ex)
        {
           Debug.WriteLine("Error: "+ex); // Nor this
        }
    }             
}
Run Code Online (Sandbox Code Playgroud)

在VS实例中调试此扩展时,我加载了一个看起来像这样的简单程序

static void Main()
{
   int x = 5;
   Console.WriteLine("X is "+x); // Breakpoint on this line
}
Run Code Online (Sandbox Code Playgroud)

当在调试过程中遇到断点时,将调用该处理程序并且扩展的输出窗口显示为"3",因此计算表达式可以工作,但它永远不会成功执行该语句.输出窗口中不会再打印任何内容.没有异常或超时发生,我无法继续调试过程,调试器似乎已崩溃.

globals类只保存DTE和DebuggerEvents

public static class Globals
{
   public static void Init(DTE2 dte)
   {
      Application = dte;
      DebuggerEvents = dte.Events.DebuggerEvents;    
   }

   public static DTE2 Application { get; private set; }
   public static DebuggerEvents DebuggerEvents { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

我做错了什么,或者误解了吗?

Kob*_*r42 1

我对 Visual Studio 调试进行了很多修改,冻结的最终原因始终与线程处理有关:VS 允许在仅在主线程中调试时运行任何代码。所有其他线程都被禁用,如果您的调试代码依赖于不同的线程,它也会冻结。

我的猜测:您在与正在调试的线程不同的线程中初始化了 DTE。

假设结果:委托方法尝试加载与调试线程不同的初始化线程的上下文,因此它必然会被冻结。

建议的解决方案:不要使用委托方法。它们隐式地引用原始的执行上下文。相反,注册一个常规方法,并在该上下文中重新初始化您的 DTE。