Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Releasing .NET objects from VB6 code

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?

like image 524
Ben McCormack Avatar asked Dec 27 '25 16:12

Ben McCormack


2 Answers

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.

like image 171
dkackman Avatar answered Dec 31 '25 19:12

dkackman


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...

like image 29
Kris Erickson Avatar answered Dec 31 '25 18:12

Kris Erickson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!