.Dispose() 在 C# 中如何工作?
如果我编写一个使用图形或线程的类,例如,我必须实现 IDisposable 接口来编写 Dispose() 方法,否则会发生内存泄漏吗? 当 GC 到达 Dipose() 时是否运行? 如果我实现 Dispose() 方法,当“diswriting”参数为 true 时,我是否应该在类中的所有一次性字段上调用 Dispose(),还是自动调用? 什么是“非托管资源”?
所以我对此很不确定,我很感激任何能帮助我理解这些事情的东西:) 谢谢
Possible Duplicate:
Proper use of the IDisposable interface
When is Dispose necessary?
If I write a class, which uses graphics, or threads for example, must I implement the IDisposable interface to write a Dispose() method or else memory leak occurs?
Does Dipose() run when the GC reaches it?
If I implement a Dispose() method, shall I call Dispose() on all the disposable fields in the class when "disposing" parameter is true, or is it automatic?
What is "unmanaged resource"?
So I'm pretty unsure about it, I'd appreciate anything that helps me understand these things :)
Thank You
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
IDisposable
只是一个需要遵循的模式。它本身没有做任何特殊的事情(除了满足如果您正在使用本机资源,则垃圾收集器不会“知道”该资源。
IDisposable
是用于允许您确定性地释放此资源的约定。有关详细信息,我写了一个关于 IDisposable 的详细系列,其中讨论了为什么以及如何针对各种场景实现它(包括包装本机资源、封装其他 IDispsable 类型等)。
IDisposable
is just a pattern to follow. It doesn't do anything, in and of itself, special (other than fitting the requirements of the using statement).If you're working with a native resource, the resource isn't "known" to the garbage collector.
IDisposable
is the convention used to allow you to free this resource deterministically.For details, I wrote a detailed series on IDisposable which talks about why and how to implement it for various scenarios (including wrapping a native resource, encapsulating other IDispsable types, etc).