为什么GC不收集未使用的对象?
我在实验中使用 BlockingCollection 实现了生产者/消费者模式。
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,但是在从其他线程生成时它一一增加。
GC 没有从内存中收集生成的对象。尽管实现了生产者/消费者模式,为什么我的内存会增加?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
BlockingCollection
默认使用的ConcurrentQueue
.Net 4.0 中存在内存泄漏。我不确定这是您正在观察的问题,但可能是。它应该在即将发布的 .Net 4.5 中得到修复。
The
ConcurrentQueue<T>
that is used by default byBlockingCollection<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.
垃圾收集器不会始终自动释放内存。处置未使用的对象后,您可以通过调用 GC.Collect(); 来强制进行垃圾回收。
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.