在for循环中创建对象的C#内存使用情况 [英] C# memory usage for creating objects in a for loop

查看:278
本文介绍了在for循环中创建对象的C#内存使用情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个复杂的数据库转换控制台应用程序,它可以从旧数据库中读取数据,执行很多操作并放入新数据库中.

I have a complex database conversion console app that reads from an old database, does a bunch of things, and puts into the new database.

我遇到了一个不断升级的内存问题,我的内存使用率(在任务管理器中监视)不断攀升,并最终使该过程暂停.

I'm having an escalating memory problem where my mem usage (as monitored in task manager) constantly climbs and eventually slows down the process to a halt.

我将其归结为最简单的测试POC,以尝试了解正在发生的事情.

I've boiled it down to the simplest possible test POC to try and understand what's going on.

for (int i = 0; i < 100000; i++)
{
  TestObj testc = new TestObj
    {
      myTest = "testing asdf"
    };
}
public class TestObj
{
    public string myTest;
}

我的想法是,循环中创建的每个testc都不会在迭代结束后继续存在,但是内存跟踪的方式似乎是应用程序在按住testc的每个实例

My thought was that each testc that is created in the loop wouldn't survive past the end of the iteration, but the way the memory is tracking it seems like the application is holding on to every instance of testc.

我已经做了大量的研究和实验,但是我感觉这里缺少一些东西.我不应该能够运行此程序并使内存利用率保持相当恒定吗?

I've done a good amount of research and experimentation but I feel like there is something I'm missing here. Shouldn't I be able to run this and have memory utilization stay rather constant?

推荐答案

您遗漏了有关垃圾回收的一件事:GC直到需要时才会运行.因此,是的,即使在您需要清理之后就足够了,但是直到需要更多的内存时,它还是不会这样做.

You're missing one key thing about garbage collection: The GC won't run until it needs to. So yes, even though it's nice enough to clean up after you, it still won't do it until more memory is needed.

这篇关于在for循环中创建对象的C#内存使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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