我应该实施 IDisposable 来释放“非托管”吗?记忆?
假设我正在 C++/CLI 中实现一些包装类 Foo
。当然,如果我创建一个 dtor (Foo::~Foo
),它将成为一个 IDisposable
实现。
IDisposable 通常用于允许立即释放一些“稀缺”资源:GDI 资源、文件句柄等。但是,如果我的 IDisposable 只是释放内存(例如,它只是执行 free
或 delete),每当发生这种情况时,不应该在常规终结器 (
Foo::!Foo
) 中完成吗?
我的意思是,我们同意 .NET 随时释放内存的想法,那么为什么要对本质上只是释放内存的东西进行精细控制呢?
Let's say I'm implementing some wrapper class Foo
in C++/CLI. Naturally if I'll create a dtor (Foo::~Foo
), it'll become an IDisposable
implementation.
IDisposable is typically used to allow immediate release of some "scarce" resource: GDI resources, file handles etc. However, if my IDisposable simply frees memory (e.g. it simply performs free
or delete
), shouldn't it be done in a regular finalizer (Foo::!Foo
), whenever that happens?
I mean, we're okay with the idea that .NET frees memory whenever it likes to, so why give granular control over something that's essentially just freeing memory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就我个人而言,我认为尽早释放内存(即当你不需要它时)是一个很好的原则。
当然,GC 最终会启动并释放它。但是 GC 使用单个线程来调用所有终结器,如果有很多终结器要调用,这可能会对性能产生不良影响。
您可能对具有单个客户端的桌面应用程序感觉不到太大差异,但想象一下具有数百或数千个客户端的服务器应用程序。
Personally, I think that releasing memory as early as possible (i.e. as soon as you don't need it) is a good principle.
Sure, the GC will kick in and free it, eventually. But the GC uses a single thread to call all finalizers, which can have a bad impact on performance, if there are a lot of finalizers to call.
And you may not feel much difference on a desktop app with a single client, but imagine a server app with hundreds or thousands of clients.