c# - 什么是 "rooted reference"?

标签 c# reference clr

引自 Eric lippert 的 ( Safe in C# not in C++, simple return of pointer / reference, answer 3)。

Also, note that it is not any reference to the Person object that keeps it alive. The reference has to be rooted. You could have two Person objects that reference each other but are otherwise unreachable; the fact that each has a reference does not keep them alive; one of the references has to be rooted.

我不明白,谁能解释一下什么是根引用?

最佳答案

表示GC根。

通读this article ,也许它会帮助您理解:

GC roots are not objects in themselves but are instead references to objects. Any object referenced by a GC root will automatically survive the next garbage collection. There are four main kinds of root in .NET:

A local variable in a method that is currently running is considered to be a GC root. The objects referenced by these variables can always be accessed immediately by the method they are declared in, and so they must be kept around. The lifetime of these roots can depend on the way the program was built. In debug builds, a local variable lasts for as long as the method is on the stack. In release builds, the JIT is able to look at the program structure to work out the last point within the execution that a variable can be used by the method and will discard it when it is no longer required. This strategy isn’t always used and can be turned off, for example, by running the program in a debugger.

Static variables are also always considered GC roots. The objects they reference can be accessed at any time by the class that declared them (or the rest of the program if they are public), so .NET will always keep them around. Variables declared as ‘thread static’ will only last for as long as that thread is running.

If a managed object is passed to an unmanaged COM+ library through interop, then it will also become a GC root with a reference count. This is because COM+ doesn’t do garbage collection: It uses, instead, a reference counting system; once the COM+ library finishes with the object by setting the reference count to 0 it ceases to be a GC root and can be collected again.

If an object has a finalizer, it is not immediately removed when the garbage collector decides it is no longer ‘live’. Instead, it becomes a special kind of root until .NET has called the finalizer method. This means that these objects usually require more than one garbage collection to be removed from memory, as they will survive the first time they are found to be unused.

(强调我的)

关于c# - 什么是 "rooted reference"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8458886/

相关文章:

ios - 引用一个尚不存在的对象

c# - 线程是内核对象吗?

c# - 为列表编写删除名称循环

c# - 可以将泛型类型列表转换为其父类(super class)型的泛型列表吗?

Java:将属性从一个对象实例复制到另一个对象实例?

c# - 哪个是创建捕获变量/闭包的代码?

Silverlight 5 - 如何在 XAML 中使用普通 CLR 对象作为 CommandParameter?

c# - xamarin 中带有 NSUrlSessionDelegate 的客户端证书

c# - Get 方法的大小

mysql - MySQL-docu 中提到的 "table_reference"是什么?