Interop - Object Lifetime

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a class called Manager. In the 'Initialize' method of the Manager
class, I create an instance of a COM class (say oComObject). What is the
lifetime of oComObject. Will it be available as long as the 'Manager' object
is in memory?

Is there any difference in object lifetime with and without Interop?
 
Tim,

In the Initialize method, do you store the reference in a field in the
class, or is it a variable on the stack? If it is on the stack, then when
the reference is let go, it makes the wrapper eligible for GC, and the COM
object will be released on the next GC. If it is stored in the object, then
when your object is eligible for GC, then the wrapper is eligible for GC.

Both cases assume that you do not pass the reference outside of the
method or class.

If you are using your COM object in your method only, then you can pass
the object to the static ReleaseComObject method on the Marshal class, and
it will release the object (assuming that you are the only one who had a
reference to it).

If you are storing it in your class, then you should call the
ReleaseComObject method in an implementation of IDisposable.

Hope this helps.
 
Hi Nicholas,

Thank you for the informative response. In my case, the ComObject's
reference is stored in a field in the class. Then based on your respose, I
need to call ReleaseComObject method in an implementation of IDisposable.

But, Why do I have to call ReleaseComObject? Will it not be released
automatically when it is eligible for GC? Also, can I call ReleaseComObject
in the Terminate method of the class or is it essential to do so in an
implementation of IDisposable?



Nicholas Paldino said:
Tim,

In the Initialize method, do you store the reference in a field in the
class, or is it a variable on the stack? If it is on the stack, then when
the reference is let go, it makes the wrapper eligible for GC, and the COM
object will be released on the next GC. If it is stored in the object, then
when your object is eligible for GC, then the wrapper is eligible for GC.

Both cases assume that you do not pass the reference outside of the
method or class.

If you are using your COM object in your method only, then you can pass
the object to the static ReleaseComObject method on the Marshal class, and
it will release the object (assuming that you are the only one who had a
reference to it).

If you are storing it in your class, then you should call the
ReleaseComObject method in an implementation of IDisposable.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Tim said:
I have a class called Manager. In the 'Initialize' method of the Manager
class, I create an instance of a COM class (say oComObject). What is the
lifetime of oComObject. Will it be available as long as the 'Manager'
object
is in memory?

Is there any difference in object lifetime with and without Interop?
 
Back
Top