.NET为什么不像Java一样具有SoftReference和WeakReference? [英] Why doesn't .NET have a SoftReference as well as a WeakReference, like Java?

查看:75
本文介绍了.NET为什么不像Java一样具有SoftReference和WeakReference?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很喜欢WeakReference的.但是,我希望有一种方法可以告诉CLR您认为参考有多弱(例如,以1到5的等级).那太好了.

Java具有SoftReference,WeakReference,并且我相信它也是第三种类型,称为幻像引用".那是3个级别,GC在决定该对象是否得到印章时具有不同的行为算法.

我正在考虑将.NET的WeakReference子类化(幸运的是,有点奇怪,它没有被密封),以创建基于到期计时器或其他东西的伪SoftReference.

我相信NET没有软引用的根本原因是因为它可以依赖带有虚拟内存的操作系统. Java进程必须指定其最大OS内存(例如,使用-Xmx128M),并且从不占用更多的OS内存. NET进程不断占用其所需的OS内存,而RAM耗尽时,OS会提供磁盘支持的虚拟内存.如果NET允许软引用,则NET运行时将不知道何时发布它们,除非它深入操作系统以查看其内存是否实际上已在磁盘上分页(讨厌的OS/CLR依赖项),或者它要求运行时执行以下操作:指定最大的进程内存占用量(例如,等价的-Xmx).我猜想微软不想将-Xmx添加到NET,因为他们认为操作系统应该决定每个进程获得多少RAM(通过选择要在RAM或磁盘上保留的虚拟内存页),而不是进程本身./p>

I really love WeakReference's. But I wish there was a way to tell the CLR how much (say, on a scale of 1 to 5) how weak you consider the reference to be. That would be brilliant.

Java has SoftReference, WeakReference and I believe also a third type called a "phantom reference". That's 3 levels right there which the GC has a different behaviour algorithm for when deciding if that object gets the chop.

I am thinking of subclassing .NET's WeakReference (luckily and slightly bizzarely it isn't sealed) to make a pseudo-SoftReference that is based on a expiration timer or something.

解决方案

I believe the fundamental reason that NET does not have soft references is because it can rely on an operating system with virtual memory. A Java process must specify its maximum OS memory (e.g. with -Xmx128M), and it never takes more OS memory than that. Whereas a NET process keeps taking OS memory that it needs, which the OS supplies with disk-backed virtual memory when RAM runs out. If NET allowed soft references, then the NET runtime would not know when to release them unless it either peeked deep into the OS to see if its memory is actually paged on disk (a nasty OS/CLR dependency), or it requested the runtime to specify a maximum process memory footprint (e.g. an equivalent of -Xmx). I guess that Microsoft does not want to add -Xmx to NET because they think the OS should decide how much RAM each process gets (by choosing which virtual memory pages to hold in RAM or on disk), and not the process itself.

这篇关于.NET为什么不像Java一样具有SoftReference和WeakReference?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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