为什么CLR不调用自动处理 [英] Why doesn't the CLR call Dispose automatically

查看:140
本文介绍了为什么CLR不调用自动处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我能正确了解我的事实,如果不正确,请纠正我.

1)您使用Dispose清理非托管资源,这意味着不会对其进行垃圾回收.

2)值类型存储在堆栈上,引用类型存储在堆上,指向引用类型的指针存储在堆栈上(对此不确定(但我不确定,但我认为是正确的))

3)垃圾过滤器由垃圾收集器调用.

4)对于引用类型,CLR而不是用户(尽管他可以)调用垃圾回收,但是当值类型超出范围时,值类型将被破坏(对不起,找不到更好的词)

我知道using语句及其工作方式,但我认为,如果CLR为用户调用Dispose,会容易得多.

所以我的问题是这样的:"如果引用类型的指针存储在编译器和CLR的堆栈中,则知道对象何时超出范围.为什么编译器不生成一些调用Dispose的IL代码? ,或者为什么CLR不像Finilizers和De析构函数那样做到".

很抱歉,如果我的问题不清楚,我很乐意将其与您需要的任何其他信息一起更新. 谢谢.

解决方案

问题出在这里:

如果引用类型的指针存储在编译器和CLR的堆栈中,则知道对象何时超出范围

这太过简单了.您可以使用私有字段,这些私有字段是一次性的.这些将不会存储在堆栈中,并且CLR无法知道何时不再使用该对象,除非通过使用垃圾回收.当然,垃圾收集已经提供了一种终结器机制,您可以通过该机制来处理非托管资源.

I'm hoping i know my facts correctly if not please correct me.

1) You use Dispose to clean unmanaged resources, that means no garbage collection for them.

2) Value types are stored on the stack, reference types are stored on the heap and pointers to reference types are stored on the stack(not really sure about this one but i think it's correct)

3) Finilizers are called by the Garbage Collector.

4) Garbage Collection is called by the CLR and not by the user(although the he can) for reference types, but value types are destroyed(sorry couldn't find a better word) when they go out of scope

I know about the using statement and the way i works but i think it would be a lot easier if the CLR would call Dispose for the user.

So my question is this: "If pointers to reference types are stored on the stack the compiler and the CLR, know when the object goes out of scope. Why does the compiler not generate some IL code that calls Dispose, or why doesn't CLR do that like they do for Finilizers and Destructors".

Sorry if my question is not clear, i'll gladly updated it with any other information you need. Thank you.

解决方案

Here's the problem:

If pointers to reference types are stored on the stack the compiler and the CLR, know when the object goes out of scope

That's an oversimplification. You can have private fields which are types that are disposable. These will not be stored on the stack, and the CLR cannot know when the object is no longer in use other than through the use of Garbage Collection. And of course, Garbage Collection already provides a mechanism - the finalizer - through which you can dispose unmanaged resources.

这篇关于为什么CLR不调用自动处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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