问题描述
当我读到在C#中的内存管理的几篇文章,我被释放方法混淆。
When I read a few articles about memory management in C#, I was confused by Finalizer methods.
有与之相适应的相关这么多复杂的规则。
例如,没有人知道什么时候终结将被调用,他们呼吁即使在构造函数代码抛出,CLR并不能保证所有的终结时调用程序shutdowt等。
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?
只是一个例子,我发现程序GC启动时,它会发出蜂鸣声。
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:
当developpers要确保终结可用一些类总是通过IDisposable的正确处置。 (;感谢史蒂夫汤森)
Finalizers can be used when developpers want to make sure that some class always disposed correctly through IDisposable. (link ; Thanks Steve Townsend)
推荐答案
有是终结用法的详尽的讨论,结合实例,的。在
There is an exhaustive discussion of Finalizer usage, with examples, here. Link courtesy of @SLaks at a related answer.
另请参见这里
There's a nice prior answer here with another good real-world example.
要与相关的摘录总结:
需要终结,以保证稀缺资源的
释放回
的操作系统,如文件句柄,插座,
内核对象,等等。
有关更多的正确真实世界的例子,浏览各地的影响班.Net框架这个MSDN搜索:
For more correct real-world examples, browse around affected classes in the .Net Framework this MSDN search:
的 http://social.msdn.microsoft.com/Search/en-US?query=%22.Finalize%22&ac=8
一个有效的原因,我能想到的,如果你在一个托管包装包装第三方本机代码API时,您可能需要使用一个终结是,和底层本机代码API库需要使用操作系统资源的及时释放。
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.
这篇关于在C#中使用终结的好样本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!