Question

Is there any way to run code when COM object is about to be disconnected from RCW without implementing IDisposale interface and explicit call MyObject.Dispose in client code?

The code below is not working. When program enters Finalize sub, ExcelApplication is already disconnected from RCW, and I get error. I understand why it happens, but I want to get a solution.

I want to make it working the following way: when last managed reference is released, code from Finalize sub is executed before COM object is disconnected.

My question is - is it possible at all and if it is then how can I handle this event inside the class, without need to call Finalize explicitly from outside?

Very simple class:

Public Class ExcelRunner

  Dim ExcelApplication As Excel.Application

  Public Sub New()

    ExcelApplication = New Excel.Application
    ExcelApplication.Visible = True

  End Sub

  Protected Overrides Sub Finalize()

    MyBase.Finalize()
    ExcelApplication.Quit()

  End Sub

End Class

This class is used on form - just a single line

Dim ExcelRunner as ExcelRunner = new ExcelRunner

Then I close the form, and receive error.

Thanks

Was it helpful?

Solution

It sounds like you want to receive a notification about an RCW being disconnected just before it happens. If so there is unfortunately no such way to hook into that. Your code needs to instead account for the possibility that it's unexpectedly disconnected

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top