调试器启动时如何附加第二个进程?

时间:2013-07-16 17:46:30

标签: c# visual-studio envdte

当调试器开始使用代码时,我正在尝试连接第二个进程:

DTE dte = BuildaPackage.VS_DTE;

EnvDTE.Process localServiceEngineProcess = dte.Debugger.LocalProcesses
    .Cast<EnvDTE.Process>()
    .FirstOrDefault(process => process.Name.Contains("ServiceMonitor"));

if (localServiceEngineProcess != null) {
    localServiceEngineProcess.Attach();
}

在调试器未运行时它工作正常,但在VS_DTE.Events.DebuggerEvents.OnEnterRunMode事件期间尝试连接时尝试连接时,我收到错误:

A macro called a debugger action which is not allowed while responding to an event or while being run because a breakpoint was hit.

如何在调试器启动时立即连接到另一个进程?

1 个答案:

答案 0 :(得分:1)

我确实找到了答案,这是一个狡猾的解决方案,但如果有人提出更好的答案,我很乐意听到。本质上,您在调试器实际开始运行之前附加调试器。考虑:

internal class DebugEventMonitor {

    // DTE Events are strange in that if you don't hold a class-level reference
    // The event handles get silently garbage collected. Cool!
    private DTEEvents dteEvents;

    public DebugEventMonitor() {
        // Capture the DTEEvents object, then monitor when the 'Mode' Changes.
        dteEvents = DTE.Events.DTEEvents;                     
        this.dteEvents.ModeChanged += dteEvents_ModeChanged;
    }

    void dteEvents_ModeChanged(vsIDEMode LastMode) {
        // Attach to the process when the mode changes (but before the debugger starts).
        if (IntegrationPackage.VS_DTE.DTE.Mode == vsIDEMode.vsIDEModeDebug) {
            AttachToServiceEngineCommand.Attach();
        }
    }

}