Garbage Collector no more references
I've been reading about GC in C# and I find some statements quite amusing to be real.
Say I have the following method:
public void Foo()
{
Animal eAnimal = new Animal();
eAnimal.Name = "Matthew";
GC.Collect();
...more code not using eAnimal...
return;
}
Supposedly in the GC.Collect() statement, the GC figures out that the memory address corresponding the the new Animal() object is not longer referenced in the code and thus is appropriate to dispose.
As far as I know, even in the GC.Collect() statement, there's a reference to the new Animal() in the stack (even maybe stored in some CPU registry). I know that if I inspect the code although that value exists in the stack, in the logic of the code is not longer used, but this kind of analysis I guess could be done in the compilation time and not really in runtime.
How does the GC knows that even if there's a reference in the stack to the heap, that reference it isn't gonna be used in any way in future statements of the program?.
My best guess is that the compilation takes this into account and creates appropriate instructions that cleans that reference in the stack and then makes the GC job more easy. But this seems to add a lot of overhead to the generated code.
Edit: I'm reading a book about the exam 70-483 and it states:
StreamWriter stream = File.CreateText(“temp.dat”);
stream.Write(“some data”);
GC.Collect()
When running this piece of code in Release mode, the garbage collector will see that there are no more references to stream, and it will free any memory associated with the Stream- Writer instance.
You're not returning a reference to that object from your method, so when you call GC.Collect()
, it looks at where the object is being used and sees that nothing else will reference it after the collection call. As you indicated, none of the code after the call uses the object, so GC will safely dispose of it.
The MSDN Example does a fine job of explaining a similar situation to what you have.
A comprehensive explanation of garbage collection operation: http://msdn.microsoft.com/en-us/magazine/bb985010.aspx
链接地址: http://www.djcxy.com/p/79102.html上一篇: C ++内存管理引用类型
下一篇: 垃圾收集器没有更多的参考