【问题标题】:Simple app with timer is eating memory away?带计时器的简单应用程序正在消耗内存?
【发布时间】:2010-08-04 14:50:17
【问题描述】:

谁能解释为什么这个小应用程序的内存使用量不断增加?

static class Program
{
    private static System.Timers.Timer _TestTimer;

    [STAThread]
    static void Main()
    {
        _TestTimer = new System.Timers.Timer();
        _TestTimer.Interval = 30;
        _TestTimer.Elapsed += new System.Timers.ElapsedEventHandler(_TestTimer_Elapsed);
        _TestTimer.Enabled = true;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    static void _TestTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        string test = "tick";
        Trace.WriteLine(test);
        test = null;
    }
}

谢谢! 鼠兔81

【问题讨论】:

  • 我们在这里说话的速度有多快?
  • 另外,内存使用量是否稳定/上限在一定水平?
  • @Greg - 你知道我们也不知道Form1 发生了什么。
  • @ChaosPandion:你是对的。空的 _TestTimer_Elapsed 处理程序仍然表现出相同的症状。我的最佳猜测是每次事件触发时都会创建新的 ElapsedEventArgs。
  • @theburningmonk:它从大约 3.544k 开始,10 分钟后,它以 5.384k 进入并稳定下来。我打开 DbgView 观察痕迹,然后突然跳到 6.360k。偶尔,它会丢失几个字节,但不会很多(4 到 16 个字节)

标签: c# .net winforms memory-management timer


【解决方案1】:

您假设内存使用量不应增加。错误的假设,这只是 不是 .NET 垃圾收集器或 Windows 堆管理器的工作方式。它们都通过使用可用内存而不是不断释放和重新分配内存来有效地工作。

让它运行一周。如果您使间隔更小,可能会更快。同时最小化形式以获得壮观的效果。

【讨论】:

    【解决方案2】:

    我的建议是启动 Windbg 并找出内存中存在哪些对象。
    同意我们的开发人员通常将其用作最后一个选项,但在这种情况下,它将为您提供内存增加的确切原因

    【讨论】:

    • 我运行了一个分析器,GC 在 5 分 30 秒和 14 分 14 秒后运行。字符串实例似乎已被清理干净。任务管理器不可信。
    【解决方案3】:

    我正在挖掘DefaultTraceListener 的来源,我发现了这个:

    private void WriteLine(string message, bool useLogFile)
    {
        if (base.NeedIndent)
        {
            this.WriteIndent();
        }
        this.Write(message + "\r\n", useLogFile);
        base.NeedIndent = true;
    }
    

    因此内存使用量增长可能太慢,GC 无法立即做出反应。

    【讨论】:

      【解决方案4】:

      如果您只是查看任务管理器来查看您的进程使用了​​多少内存,您可能无法获得非常准确的读数。

      阅读这篇文章: http://www.itwriting.com/dotnetmem.php

      它解释了使用 TaskManager 作为衡量 .Net 应用程序内存使用情况的方法的一些不足之处。

      【讨论】:

        猜你喜欢
        • 2019-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-19
        • 2023-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多