带计时器的简单应用正在吃掉记忆?

时间:2010-08-04 14:50:17

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

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

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

谢谢! Pika81

4 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

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

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

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

答案 2 :(得分:1)

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

阅读本文: http://www.itwriting.com/dotnetmem.php

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

答案 3 :(得分:1)

我的建议是提高Windbg并找出记忆中存在的物体 同意我们开发人员通常将它作为最后一个选项,但在这种情况下,它会为你提供内存增加的确切原因