Managed COM component memory not released after calling "ReleaseDispatch" RRS feed

  • Question

  • I have developed a COM component in .net (c# language) which is consumed by visual c++ client. In client code, component is created and used by making calls to "CreateInstance" and "CreateDispatch" methods. When I'm done with using the COM component, I call "ReleaseDispatch" method to free the memory. But what I can see is calling "ReleaseDispatch" only reduces the reference count and actual memory is not freed. COM component still occupies the memory and after a long time this memory is freed. 

    I understand that this could be because the .net framework's garbage collector can not immediately collect the memory of the component because of it's indeterministic behaviour. Can any one confirm my this understanding?

    My requirement is such that I need to recollect the memory and make the COM component to null immediately upon calling the "ReleaseDispatch". Can any one suggest me the way to achieve this? (As far as possible, I would like to change the code on tha component side and not on the client side.)

    I hope, I'm clear with my question. 

    Thank you, 

    Krunal C
    Tuesday, December 9, 2008 9:44 AM


  • Your C++ code is fully in control of the lifetime of the COM object.  If the C# code allocates managed memory of its own, it's hard not to, that memory won't be released until the garbage collector runs.  That might take a long while if the COM object is the only managed code that runs in your app.  There's not that much you can do about that, other than adding a Destroy() method to your COM class that sets all object references to null and calls GC.Collect().  Or use more managed code :)
    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Monday, December 15, 2008 12:49 PM
    Tuesday, December 9, 2008 2:51 PM