none
RCW reference count with events RRS feed

  • Question

  • Hello all, I have a question similar to this unresolved question:

    http://stackoverflow.com/questions/3785118/removing-com-event-handlers-automatically-in-c

    I have a simple COM object and a simple C# sharp program.  The COM object has a single event on it:

     

        [STAThread]
        static void Main()
        {
          MyObject obj = new MyObject();
          obj.MyEvent += MyEventHandler;
        }
    

     


    The RCW does not seem to handle this gracefully.  The Unadvise on MyObject does not get called before the RCW is "separated" from its COM object, which causes an InvalidComObjectException.

    Here is the log from the COM object:

    22526234: Calling FinalConstruct
    22526234: Calling Advise
    22526234: Calling FinalRelease

    And the stack trace:

    mscorlib.dll!System.Runtime.InteropServices.ComEventsSink.Unadvise() + 0x20 bytes   
    mscorlib.dll!System.Runtime.InteropServices.ComEventsSink.RemoveAll(System.Runtime.InteropServices.ComEventsSink sinks) + 0x11 bytes
    mscorlib.dll!System.Runtime.InteropServices.ComEventsInfo.Finalize() + 0x18 bytes   

    Does anyone have any insight on this problem?

    Things I have tried:

    Removing [STAThread] - Causes the code to work correctly, but it not a real solution.

    Adding a ref to the COM object on Advise, releasing on Unadvise - I did this because I thought perhaps the COM object was getting released early.  Doesn't help, since the RCW detaches regardless of whether or not the underlying COM object is released.

    Removing the event handler manually - Fixes the problem (at the cost of complexity)

    Monday, August 1, 2011 9:09 PM

All replies