Reference Counting

  • Thread starter Thread starter MP
  • Start date Start date
M

MP

Hello everyone,
I am an old C++/COM programmer that converted about 8 months ago to
C#/.Net, and I have no regrets.

I am now converting our caching subsystem from COM to .Net and I have a
little problem to resolve. Our old COM cache would cleanup "unreferenced"
entities by checking the refcount on the entities in the cache. Whenever the
refcount was equal to 2 (this means the cache had a reference and the
cleanup had another) then we knew the entity was not referenced by the
application and it would get "destroyed".

I undestand that .Net does not use refcounting, but I am confused as to
how I could cleanup in .Net. Can someone point me in the rigth direction?

Thank you!

-MP.
 
In addition to Alex's response, if you're going to be implementing your own
caching system, have a look at the MSDN documentation for WeakReference.
This allows you to hold references to items that can still be garbage
collected, assuming no strong references to them exist. It has an IsAlive
property to allow you to check if the object is still in memory. It's
theoretically similar to having a COM pointer to an object without calling
AddRef(). Since a garbage collection might only collect the object some time
after all strong references to it are cleared, holding onto the weak
reference acts as quite a nice caching mechanism.

Of course, you'd probably be better off using an existing caching system
(such as the Caching Application Block).
 
CRL manages reference counting automatically. To make it call Release() all
you need is to assign null to the COM object reference. It will mark the
object for garbage collction. There is another possibility of calling
Release() explicitly from the code like this:

using System.Runtime.InteropServices;

IntPtr intptr = Marshal.GetIUnknownForObject(comObject);
int count = Marshal.Release(intptr);
 
Thank you Shaun,
I will look at this as well, seems like the ideal solution.

About the Caching Application Block, do you have some experience with it?
I will read about it.

Thank you !

-MP
 
Microsoft just released their new enterprise blocks. This is re-working (I
believe) of the current blocks.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag2/html/entlib.asp

Current blocks had lots of dependencies and were implemented differently
across the blocks, the new enterprise blocks are suppose to give the blocks
a more consistent feel across blocks. Also some of the dependencies were
removed (again I believe this to be true)

--
Thanks
Wayne Sepega
Jacksonville, Fl


"When a man sits with a pretty girl for an hour, it seems like a minute. But
let him sit on a hot stove for a minute and it's longer than any hour.
That's relativity." - Albert Einstein
 
Back
Top