处理非托管对象的托管对象代理图
我的问题与此类似: 管理托管的析构函数(C# ) 和非托管 (C++) 对象
但有一点不同。
本质上,我有一个对象图或层次结构,其中类 Foo
拥有对类 Bar
的多个实例的一些引用(等等)。
在 .NET 中,我有一个托管表示Foo
维护真实 Foo
的 IntPtr
并使用 P/Invoke 调用真实 Foo
上的方法(作为代理人)。
我的 Foo
(代理)的托管实现实现了 IDisposable
。
代理 Foo
包含一个 List
类型的只读属性。
我的托管 Bar 代理的工作方式相同(保留它代表的真实 Bar 的 IntPtr)。
当真正的 Foo
被释放时,它会释放它的所有子级(包括所有 Bar
)。
处理这种情况的最佳方法是什么 - 因为我不希望 Foo 代理的托管客户端获取对 Bar 的引用并保留它大约比他们引用 Foo
代理的时间还要长。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许我对此过于简化了,但是您的
Bar
(代理)类应该有一个由父/所有者Foo
调用的Dispose
方法> 类。与许多类一样,一旦Bar
对象被释放,它应该将内部m_dispose
标志设置为 true,并在以下情况下抛出ObjectDispose
异常:其方法随后使用。您不应该关心客户端是否具有对托管 Bar 对象的引用,只要其内部非托管资源已被清理即可。Perhaps I'm over-simplifiying this, but your
Bar
(proxy) class should have aDispose
method that is called by the parent/ownerFoo
class. And like many classes, once theBar
object has been disposed it should set an internalm_disposed
flag to true and throw anObjectDisposed
exception if any of its methods are used afterward. You shouldn't care if the client has a reference to the managedBar
object as long as its internal unmanaged resources have been cleaned up.我刚刚实现了一个简单的引用计数方案。
我希望还有其他方法,但是,最终,它很简单,而且确实是正确的解决方案。
I just implemented a simple reference counting scheme.
I was hoping there would be some other way, but, at the end of the day, it was simple, and was really the correct solution.