views:

60

answers:

2

On .NET Rocks! Show 561, Carl and Richard talked about releasing unmanaged objects instantiated in managed code. If you have to release a COM object that's instantiated in managed .NET code, you have to call System.Runtime.InteropServices.Marshall.ReleaseComObject. Is there anything similar you have to do (or should do) when releasing .NET objects from COM code, or is it sufficient to rely on the Garbage Collector to release the objects?

+4  A: 

As long as you manage the ref count of the COM Callable Wrapper like you do any other COM object (set netObj = Nothing) COM and .NET will take care of the rest.

dkackman
+1. I'll just mention that often you don't need to do anything. If `netObj` is a local variable, the VB6 runtime will release it immediately at the end of the routine. You only need to `Set netObj = Nothing` if `netObj` is a module level variable or a global.
MarkJ
+3  A: 

I would also add that if you use events from VB6, you will want to add a function in your DotNet code to release the Event. E.g.:

class SomeEventClass
{
    public event EventHandler SomeEvent;

    public void DoSomething()
    {
        var someEvent = SomeEvent;
        if (someEvent != null)
        {
             someEvent(this, new EventHandlerArgs());
        }
    }

    public void ReleaseFromEvents()
    {
         SomeEvent = null;
    }

}

This is necessary as sometimes the event will not be cleared to null when the VB6 object is destroyed. Something learned the hard way...

Kris Erickson