GC移动对象时,Object.GetHashCode如何工作? [英] How does Object.GetHashCode work when the GC moves an object?

查看:102
本文介绍了GC移动对象时,Object.GetHashCode如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我理解正确,则在.NET中, Object.GetHashCode()的默认实现返回基于对象的内存地址的值(至少对于引用类型而言) 。但是,垃圾收集器可以随意在内存中移动对象。大概哈希码不会仅仅因为GC移动了一个对象而发生了变化,那么这种交互是否需要特殊的处理,还是我的假设是错误的?

解决方案

它不基于该地址返回值。



第一次为 object.GetHashCode

c>被称为(不被覆盖时),该对象的锁上存在争用。 (如果您也调用Wait / Pulse / PulseAll,也可能会分配它,我也没看过。)



sync块与对象主数据的位置无关在记忆中。基本上(据我了解),有一个用于同步块的大表-该表以某种方式保持有效,部分原因是并非每个对象都需要一个(仅需要系统哈希码或锁定对象)。


If I understand correctly, in .NET the default implementation of Object.GetHashCode() returns a value based on an object's memory address (at least for reference-types). However, the garbage collector is free to move objects around in memory. Presumably the hash code doesn't change just because the GC moves an object, so is there special handling for this interaction, or are my assumptions wrong?

解决方案

It doesn't return a value based on the address. It returns a value based on the sync block for the object.

The sync block is allocated the first time object.GetHashCode is called (when not overridden) or there's contention on the lock for the object. (It may be allocated if you call Wait/Pulse/PulseAll too, I haven't looked.)

The sync block is independent of the location of the object's main data in memory. Basically (as I understand it) there's one big table for sync blocks - which is kept efficient in some fashion, partly due to not every object requiring one (only ones where the system hashcode is required, or locking).

这篇关于GC移动对象时,Object.GetHashCode如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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