次の方法で共有


Simple VS Addin (updated)

Back during the PDC for Whidbey I wrote a post about Creating a Simple Addin. Recently I was looking to update it and found a horrible bug in it. First, here is the corrected code:

 

public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)

{

    _applicationObject = (DTE2)application;

    _addInInstance = (AddIn)addInInst;

    _debuggerEvents = _applicationObject.Events.DebuggerEvents;

    _debuggerEvents.OnEnterBreakMode += new _dispDebuggerEvents_OnEnterBreakModeEventHandler(DebuggerEvents_OnEnterBreakMode);

}

private DebuggerEvents _debuggerEvents;

private System.Collections.Generic.Queue<EditPoint> epQ = new System.Collections.Generic.Queue<EditPoint>();

void DebuggerEvents_OnEnterBreakMode(dbgEventReason Reason, ref dbgExecutionAction ExecutionAction)

{

    TextDocument td = (TextDocument) _applicationObject.ActiveDocument.Object("TextDocument");

    EditPoint ep = td.Selection.ActivePoint.CreateEditPoint();

    ep.SetBookmark();

    epQ.Enqueue(ep);

    if (epQ.Count > 5)

    {

        epQ.Dequeue().ClearBookmark();

    }

}

I've changed a couple of things. I now create the Editpoint first and use it to set the bookmark rather than setting the bookmark on the selection then creating an editpoint. This removes that possibility that I save a different place then where I set the bookmark. 

The more important issue is I keep a member variable for _applicationObject.Events.DebuggerEvents. Why? Because it keeps that event provider from getting garbage collected. I had made the assumption that the lifetime of _applicationObject.Events.DebuggerEvents would be strictly tied to the DTE object, and managed by automation. That is not the case. The way this bug manifests is pretty ugly since the Addin works as expected for a while, until the Event Provider (_applicationObject.Events.DebuggerEvents) is collected and Finalized, at which point the events just stop coming. 

I wasn't sure if this was by design or not. However, I found this KB article: Visual Studio .Net events being disconnected from add-in, so I am going with it being by design.

Comments

  • Anonymous
    January 04, 2006
    What were u expecting ? That's how garbage collectors work....and that's how scoping works... In these days people dumped with too much work donot take the time to sit down with a pencil and paper and look at their code and trace it slowly....
  • Anonymous
    June 01, 2009
    PingBack from http://indoorgrillsrecipes.info/story.php?id=5549