了解 gcroot
我一直在阅读这篇文章来了解gcroot 模板。我明白了
gcroot 提供句柄 垃圾收集堆
和那个
句柄本身不是垃圾 已收集。
我不明白的是以下内容:
当 CLR 对象随着 垃圾收集堆,句柄 将返回的新地址 目的。变量不一定是 在将其分配给之前固定 gcroot 模板。
这是否意味着即使有 gcroot 句柄引用该对象,CLR 对象也会被垃圾收集器删除?
它指的“新地址”是什么? “变量在分配给 gcroot 模板之前不必固定”是什么意思?
I have been reading this article to understand the gcroot template. I understand the
gcroot provides handles into the
garbage collected heap
and that
the handles themselves are not garbage
collected.
What I don't understand is the following:
When the CLR object moves with the
garbage-collected heap, the handle
will return the new address of the
object. A variable does not have to be
pinned before it is assigned to a
gcroot template.
Does that mean that the CLR object will be deleted by the garbage collector even if there is a gcroot handle referencing that object?
What is the "new address" that it refers to? And what does it mean that the "variable does not have to be pinned before it is assigned to a gcroot template"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
垃圾收集不仅仅删除未引用的对象,它还会移动仍然引用的对象,例如对空闲内存池进行碎片整理。当文章谈论在 CLR 堆中移动的对象时,它可能是在说“当垃圾收集移动仍然引用的对象时,gcroot 句柄将自动更新以仍然指向 CLR 对象”。
您可以使用
pin_ptr
关键字来阻止 GC 移动对象,如下所示:请参阅 这篇文章了解有关固定的更多信息。
观察:这篇文章可能有错字。如果它说“在垃圾收集堆内”而不是“在垃圾收集堆中”,这会提高你的理解吗?文章中的措辞方式听起来就像每当 GC 清理房屋时,地球都会在你脚下移动。
Garbage collection doesn't just remove unreferenced objects, it also moves around objects that are still referenced, e.g. to defragment the free memory pool. When the article talks about objects moving in the CLR heap, it's probably saying "when garbage collection moves a still-referenced object, the gcroot handle will be automatically updated to still point to the CLR object."
You can prevent GC from moving objects around by using the
pin_ptr
keyword, like so:See this article for more information about pinning.
Observation: The article may have a typo. If it had said "within the garbage-collected heap" instead of "with the garbage-collected heap", would that have improved your understanding? The way it's phrased in the article makes it sound like the very earth would move under your feet whenever GC cleaned house.