Quantcast
Channel: Common Language Runtime Internals and Architecture forum
Viewing all articles
Browse latest Browse all 1710

Finalization of .NET COM exposed component (CCW)...

$
0
0

Hi everyone!

Here's my problem :
COM has a deterministic way of freeing components (when reference counter hits 0), whereas NET uses a garbage collector for memory management... (so far so good :p)

When exposing a .NET component to COM, the runtime makes a bridge between the two worlds through a nice CCW (http://msdn.microsoft.com/en-us/library/f07c8z1c.aspx) which is responsible for releasing the reference on the managed object when the COM reference count reaches 0.

Now... how can I implement a equivalent of the VB6 Class_Finalize() method in C# ?

* Destructors are called only when the GC is run which is completly not deterministic....
* IDisposable pattern seems not to be used by the CCW (or did I miss something ?)

Here's a simple example :

namespace MyComLibrary
{
    [ComVisible(true)]    
    [Guid("5E9054E9-5EC9-38E2-BE1F-B94848BD3BFB")]
    public interface IClass
    {
        string Hello();
    }    

    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    [Guid("2281177C-458A-3939-92A3-4132F373C853")]        
    public class Class : IClass
    {
        public Class()
        {
        }
        ~Class()
        {
        }

        public string Hello()
        {
            return "Hello world !";
        }                
    }
}

Called by the following VB script :

Option Explicit

Dim oCls

Set oCls = CreateObject("MyComLibrary.Class")
    WScript.Echo("Calling")
WScript.Echo(oCls.Hello())
    WScript.Echo("Not released")
WScript.StdIn.ReadLine()
Set oClS = Nothing
    WScript.Echo("Released")
WScript.StdIn.ReadLine()
    WScript.Echo("Finished")

Put a breakpoint on the finalizer and debug : it's never called !

So as far as I understand it, the only way is to add a public Close or Dispose method and ensures callers actually call it before releasing the object ? (Which would make reference counting kindda useles...)

Any ideas are welcome !

Thanks for reading me,
Ludovic.


Viewing all articles
Browse latest Browse all 1710

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>