oguzh4n
oguzh4n

Reputation: 682

Why GC does not collect unused objects?

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?

Upvotes: 1

Views: 1259

Answers (2)

svick
svick

Reputation: 244757

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.

Upvotes: 6

Dennis Traub
Dennis Traub

Reputation: 51634

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.

Upvotes: 0

Related Questions