C#垃圾收集 [英] C# Garbage collection

查看:119
本文介绍了C#垃圾收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我们有:

 公共无效美孚()
{
someRefType测试=新someRefType ();
测试=新someRefType();
}



什么是垃圾收集器做的第一个堆对象?是正好在垃圾新的分配之前收集的?一般的机制是什么?谢谢,克林斯曼


解决方案

什么是垃圾收集器做的第一个堆对象?




谁知道呢?这不确定性。想想看这样的:用无限的内存的系统上,垃圾收集器不的有无的做的任何的。你可能会认为这是一个坏的榜样,但是这就是垃圾收集器模拟为您提供:用无限怀念的系统。由于可用比要求你的程序充分更多的内存的系统上,垃圾收集器的从不的具有运行。因此,你的程序不能进行内存的时候会(如果有的话)收集有关的任何假设



所以,回答你的问题是:我们不知道。




时,它会立即垃圾的新的分配之前收集的?




没有。垃圾收集器不确定性。你不知道什么时候会收集和发布垃圾。你不能让当垃圾将被收集时或终结将运行任何假设。



在实际上,这是不太可能它收集如此之快(这将使集合发生太大经常)。此外,有足够的内存的系统上,垃圾收集器的从不的具有运行。




什么是一般机制是什么?




这是一个相当宽泛的问题。但潜在的原理很简单:垃圾收集器模拟机无限怀念。要做到这一点,它在某种程度上跟踪内存和能够确定当内存垃圾。当它认为合适的,因为它需要模拟无限怀念,它会不时地收集这些垃圾,并使其可再次分配。


say we have:

public void foo()
{
   someRefType test = new someRefType ();
   test = new someRefType ();
}

What does the garbage collector do with the first heap object? Is it immediately garbage collected before the new assignment? What is the general mechanism? Thanks, Juergen

解决方案

What does the garbage collector do with the first heap object?

Who knows? It's not deterministic. Think of it like this: on a system with infinite memory, the garbage collector doesn't have to do anything. And you might think that's a bad example, but that's what the garbage collector is simulating for you: a system with infinite memory. Because on a system with sufficiently more memory available than required by your program, the garbage collector never has to run. Consequently, your program can not make any assumptions about when memory will (if ever) be collected.

So, the answer to your question is: we don't know.

Is it immediately garbage collected before the new assignment?

No. The garbage collector is not deterministic. You have no idea when it will collect and release garbage. You can not make any assumptions about when garbage will be collected or when finalizers will run.

In fact, it's very unlikely it's collected so quickly (that would make collections happen too frequently). Additionally, on a system with sufficient memory, the garbage collector never has to run.

What is the general mechanism?

That's a fairly broad question. But the underlying principle is very simple: a garbage collector simulates a machine with infinite memory. To do this, it somehow keeps track of memory and is able to determine when memory is garbage. When it sees fit, due to its need to simulate infinite memory, it will from time to time collect this garbage and make it available for allocation again.

这篇关于C#垃圾收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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