在C#中使用终结的好样本 [英] Good samples of using Finalizers in C#

查看:126
本文介绍了在C#中使用终结的好样本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我读到在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.

另请参见这里 用于当你需要一个更简明摘要一(这是不经常)。

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.

要与相关的摘录总结:

需要终结,以保证稀缺资源的
释放回
的操作系统,如文件句柄,插座,
内核对象,等等。

Finalizers are needed to guarantee the release of scarce resources back into the operating system like file handles, sockets, kernel objects, etc.

有关更多的正确真实世界的例子,浏览各地的影响班.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#中使用终结的好样本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆