在 C# 中使用终结器的好示例
当我阅读一些有关 C# 内存管理的文章时,我对 Finalizer 方法感到困惑。
有很多复杂的规则与之相关。 例如,没有人知道何时会调用终结器,即使 ctor 中的代码抛出异常,它们也会调用,CLR 不保证在程序关闭时调用所有终结器,等等。
在现实生活中,终结器可以用于哪些用途?
我发现的唯一一个例子是 GC 启动时发出蜂鸣声的程序。
您在代码中使用终结器并且可能有一些好的示例吗?
UPD:
当开发人员希望确保某些类始终通过 IDisposable 正确处置时,可以使用终结器。 (链接;感谢Steve Townsend)
When I read a few articles about memory management in C#, I was confused by Finalizer methods.
There are so many complicated rules which related with them.
For instance, nobody knows when the finalizers will be called, they called even if code in ctor throws, CLR doesn't guarantee that all finalizers be called when programs shutdowt, etc.
For what finalizers can be used in real life?
The only one example which I found was program which beeps when GC starts.
Do you use Finalizers in your code and may have some good samples ?
UPD:
Finalizers can be used when developpers want to make sure that some class always disposed correctly through IDisposable. (link ; Thanks Steve Townsend)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此处对 Finalizer 的使用进行了详尽的讨论,并附有示例。链接由@SLaks提供,位于相关答案。
另请参阅此处了解何时需要(“不是很频繁”)的更简洁摘要。
有一个很好的先前答案这里还有另一个很好的现实例子。
用相关摘录进行总结:
有关更多正确实际示例,请浏览 .Net 中受影响的类:
https://learn.microsoft.com/en-us/search/?terms=.Finalize&scope=.NET
一个有效理由我能想到什么时候你可能需要使用终结器是如果你将第三方本机代码API包装在托管包装器中,并且底层本机代码API库需要及时释放已使用的操作系统资源。
There is an exhaustive discussion of Finalizer usage, with examples, here. Link courtesy of @SLaks at a related answer.
See also here for a more concise summary of when you need one (which is "not very often").
There's a nice prior answer here with another good real-world example.
To summarize with a pertinent extract:
For more correct real-world examples, browse around affected classes in .Net:
https://learn.microsoft.com/en-us/search/?terms=.Finalize&scope=.NET
One valid reason I can think of when you might need to use a finalizer is if you wrap a third-party native code API in a managed wrapper, and the underlying native code API library requires the timely release of used operating system resources.
据我所知,最佳实践很简单,不要使用它们。然而,当您想要使用终结器时,可能会出现一些极端情况,特别是在处理非托管对象时,并且您无法实现 Dispose 模式(我不知道遗留问题),那么您可以实现
Finalize
方法小心(它可能会降低系统的性能,使您的对象不死和其他可能奇怪的情况,请注意异常,因为它们是无法捕获的:))。99% 的情况下,只需编写使用 Dispose 模式并使用此方法自行清理,一切都会好起来的。
The best practice known to me is plain simple don't use them. There might however be some corner cases when you want to use a finalizer, particularly when dealing with unmanaged objects and you can't implement Dispose pattern (I do not know legacy issues) then you can implement
Finalize
method with caution (and it could reduce the performance of your system, make your objects undead and other possibly weird scenarios, minding the exceptions as they are uncatchable:)).In 99% of cases just write the use Dispose pattern and use this method to clean after yourself and everything will be fine.