none
RCWs and Reference Counting RRS feed

  • Question

  • Let's say I have an Outlook Add-In written using VSTO (Office 2013 / VS 2013)

    Below is an event handler for the ItemAdd event of Outlook.Items property.

    void _folderItems_ItemAdd( object Item )
    {
    
       // do something useful
    
    }

    The parameter "Item" in this case is an Outlook.AppointmentItem object.

    It's my understanding that when "Item" looses scope (returning when this handler is done) that the reference count of the RCW is not decremented and that if we want to release this reference count we should use Marshal.ReleaseComObject(...);

    This question came to mind when reading the following article: http://jpassing.com/2009/03/26/rcw-reference-counting-rules-com-reference-counting-rules/

    Compare this with the RCW reference count. As with COM, the RCW’s reference count will be incremented for you when the parameter is passed in. But unlike in COM, it won’t be decremented for you automatically when you return.
    
    You could sum up the difference like this:
    
    COM assumes you won’t be holding onto the object reference when the method returns
    The RCW assumes you *will* be holding onto the object reference when the method returns.
    So if you don’t plan to keep hold of the object reference, then the method should really look like this:
    
    public void Spong(ISomeOtherComInterface bar)
    {
      bar.Quux();
      Marshal.ReleaseComObject(bar);
    }




    Tuesday, December 16, 2014 8:49 PM

Answers

All replies