Why GC does not collect unused objects?

浪尽此生 提交于 2019-12-22 01:40:13

问题


I implemented Producer/Consumer pattern with BlockingCollection for my experiment.

PerformanceCounter c = null;
void Main()
{
    var p  =System.Diagnostics.Process.GetCurrentProcess();
    c = new PerformanceCounter("Process", "Working Set - Private", p.ProcessName);

    (c.RawValue/1024).Dump("start");
    var blocking = new BlockingCollection<Hede>();
    var t = Task.Factory.StartNew(()=>{
        for (int i = 0; i < 10000; i++)
        {
            blocking.Add(new Hede{
            Field = string.Join("",Enumerable.Range(0,100).Select (e => Path.GetRandomFileName()))
            });
        }
        blocking.CompleteAdding();
    });

    var t2 = Task.Factory.StartNew(()=>{
        int x=0;
        foreach (var element in blocking.GetConsumingEnumerable())
        {
            if(x % 1000==0)
            {
                (c.RawValue/1024).Dump("now");
            }
            x+=1;   
        }
    });
    t.Wait();
    t2.Wait();
    (c.RawValue/1024).Dump("end");
}

My memory dump after running:

start
211908
now
211972
now
212208
now
212280
now
212596
now
212736
now
212712
now
212856
now
212840
now
212976
now
213036
end
213172

My memory is 211908kb before consuming, but it increased one by one while producing from other thread.

GC did not collect the produced objects from memory. Why my memory increment although implemented producer/consumer pattern?


回答1:


The ConcurrentQueue<T> that is used by default by BlockingCollection<T> contains a memory leak in .Net 4.0. I'm not sure this is the problem you're observing, but it could be.

It should be fixed in the upcoming .Net 4.5.




回答2:


The Garbage Collector doesn't automatically free memory all the time. You can force garbage collection by calling GC.Collect(); after disposing of unused objects.



来源:https://stackoverflow.com/questions/8702544/why-gc-does-not-collect-unused-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!