Subscription to DTE events doesn't seem to work - Events don't get called

你离开我真会死。 提交于 2019-12-03 11:09:09

Posting an answer that I got from MSDN forums, by Ryan Molden, in case it helps anyone:

I believe the problem here is how the CLR handles COM endpoints (event sinks). If I recall correctly when you hit the _applicationObject.Events.DebuggerEvents part of your 'chain' the CLR will create a NEW DebuggerEvents object for the property access and WON'T cache it, therefor it comes back to you, you sign up an event handler to it (which creates a strong ref between the TEMPORARY object and your object due to the delegate, but NOT from your object to the temporary object, which would prevent the GC). Then you don't store that object anywhere so it is immediately GC eligible and will eventually be GC'ed.

I changed the code to store DebuggerEvents as a field and it all started to work fine.

Tono Nam

Here is what @VitalyB means using code:

// list where we will place events.
// make sure that this variable is on global scope so that GC does not delete the evvents
List<object> events = new List<object>();

public void AddEvents(EnvDTE dte)
{
    // create an event when a document is open
    var docEvent = dte.Events.DocumentEvents;

    // add event to list so that GC does not remove it
    events.Add(docEvent );

    docEvent.DocumentOpened += (document)=>{

        Console.Write("document was opened!");
    };

    // you may add more events:
    var commandEvent = dte.Events.CommandEvents;
    events.Add(commandEvent );

    commandEvent.AfterExecute+=  etc...

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!