I have an c# com class that is used by umamaged code. I can debug it , but I can't know when an object is released. If it had been implementd in c++ descructur would be called ,on c# it would be released to GC. Is there any way to track that moment? Thanks in advance.
Asked
Active
Viewed 381 times
5
-
Are you looking for a finalizer? – SLaks Apr 16 '12 at 18:43
-
Just curious, can you use a c# [destructor](http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx) in this situation ? – Bala R Apr 16 '12 at 18:44
-
No happy answer here. Your [ComVisible] class instance is a plain old .NET object. It is kept alive by a reference in the CCW. The final Release() call destroys the CCW but nothing happens to your .NET object. Until it gets garbage collected like normal. You'll need to debug the native code. Where the problem no doubt is located anyway. – Hans Passant Apr 16 '12 at 19:58
1 Answers
1
Managed types that maintain unmanaged resources should implement the IDisposable interface. This tells consumers of your code that they need to call Dispose()
on instances of your object(s) when they are through with them (i.e., wrap them in a using
block when possible).
A proper implementation of IDisposable
will release the native resources in their finalizer, but clients can call Dispose()
sooner than that for deterministic release of unmanaged resources. Either way you avoid a leak, but it is better to call Dispose()
as quickly as possible.
Here is an SO question which details the process.
-
The problem is that I can't control the unmanaged code. There arent any necessary cleanup that can't be done by GC. I just wish to know what is expected lifetime of my object . – user629926 Apr 16 '12 at 18:51
-
If you have no control over the native code then I don't understand the question. Managed code has no way to cleanup native code unless the native code defines an interface to do so. The GC taking care of your managed wrapper is irrelevant; it doesn't just magically cleanup the native stuff. You have to do that yourself by implementing IDisposable and calling some function on your native resources to free it. – Ed S. Apr 16 '12 at 18:59
-
I don't have any native resources for cleanup, just want to know when is managed warper realised. – user629926 Apr 16 '12 at 19:08
-
Then why are you mentioning COM at all? I am confused. Managed resources are released when the GC decides to release them. There are many resources out there on how the GC works. Why do you need to know? You can implement a finalizer, but judging from the way you have asked this question I suggest educating yourself on the subject before doing so. – Ed S. Apr 16 '12 at 19:22
-
The native code uses my class in indeterminate manner. Sometimes it uses the same objects for the whole app lifetime. Sometimes it just stops calling methots from one and instances new with same values and so on, so I wanted to know if my object is released before instancing new... – user629926 Apr 16 '12 at 19:46