COM Interop and Finalize

Our company does quite a bit of development in .NET for COM which involves the CCW. Unfortunately, some questions have arisen regarding the CCW and the C# destructor execution. Specifically, does setting the .NET object in an unmanaged environment result in a call to the destructor

I would imagine that it does not because .NET is non-deterministic, meaning that the garbage collector takes care of destroying the object - which invokes the destructor. This leads me to believe that the destructor will eventually be called by the GC. In order to test this theory, I wrote a simple object that has a destructor. The destructor simply creates a text file and writes the date and time of execution to the file.

When I create the object in the managed world, I eventually get the text file with the expected message. After deleting the text file, and then cosuming the object from a VB6 form, I never receive the text file. It does not appear that the GC ever invokes the finalize method.

I cannot find anything on the MSDN website that discusses these two concepts together, and my searches on Google have not resulted in any answers. I am hoping that someone can shed some light or point me in the right direction.



Answer this question

COM Interop and Finalize

  • James Bannan

    Ditto to Wade's post.

    Wade,

    I have a support ticket open with Microsoft right now as this appears to be a bug in the .NET runtime. I will post the findings once a conclusion is reached. I posted here in hopes that I was a complete idiot and misread some documentation, but apparently not.

    -Brian


  • haba

    I've observed the same thing calling a COM server (implemented in C#) from MS Access. I've tried using IDisposable, as well, with no luck.
  • John123

    You might need to use Marshall.ReleaseComObject. I use the following pattern


    // Declare COM object
    MyComponent.MyClass myComObject =
    null;
    try

    {
    myComObject =
    new MyComponent.MyClass();
    myComObject.MyMethod();

    }
    catch (Exception ex)
    {
    // handle as you want
    }
    finally

    {
    if (myComObject != null)
    {
    Marshal.ReleaseComObject(myComObject);
    }
    }


  • rayfusion

    Thank you for the quick response, and that is a useful pattern, but unfortunately does not apply to this problem.  My problem is not related to calling COM objects from managed code -- it's the other way around.  My managed code is called as a COM server from unmanaged code (in this case, MS Access).  When Access releases my COM object, neither Dispose() nor Finalize() are called.
  • ideal24293

    Brian:

    I could not even find documentation relating specifically to Finalize() (or Dispose()) and COM Interop. Were you able to find anything

    -Wade

  • COM Interop and Finalize