My question is similar to this one: Managing destructors of managed (C#) and unmanaged (C++) objects
But with a twist.
I have, essentially, an object graph, or hierarchy, where class Foo
owns some references to multiple instances of class Bar
(etc.)
In .NET I have a managed representation of Foo
which maintains an IntPtr
to the real Foo
and uses P/Invoke to call methods on the real Foo
(acting as a proxy).
My managed implementation of Foo
(the proxy) implements IDisposable
.
The proxy Foo
contains a readonly property of type List<Bar>
.
My managed Bar
proxy works the same way (holds unto an IntPtr
for the real Bar
it represents).
When the real Foo
is released, it releases all of it's children (including all Bar
s).
What is the best approach for dealing with this scenario - as I don't want managed clients of the Foo
proxy to get a hold of a reference to a Bar
and keep it around longer than they do their reference to the Foo
proxy.