为什么GC不收集未使用的对象? [英] Why GC does not collect unused objects?

查看:70
本文介绍了为什么GC不收集未使用的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为自己的实验使用BlockingCollection实现了生产者/消费者模式.

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");
}

运行后我的内存转储:

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

在消耗之前,我的内存为211908kb,但是从其他线程生成时,内存却一一增加了.

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

GC没有从内存中收集产生的对象.为什么虽然实现了生产者/消费者模式,但我的内存却增加了?

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

推荐答案

BlockingCollection<T>默认使用的ConcurrentQueue<T>

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.

它应该在即将发布的.Net 4.5中修复.

It should be fixed in the upcoming .Net 4.5.

这篇关于为什么GC不收集未使用的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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