views:

109

answers:

4

Hi,

Can anybody explain why this tiny app's memory usage keeps increasing ?

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

Thanks! Pika81

+1  A: 

I was digging through the source of DefaultTraceListener and I found this:

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

So the memory usage is probably growing too slowly for the GC to react immediately.

ChaosPandion
+1 for the appending Trace.
Adrian Regan
A: 

If you're only looking at the Task Manager to see how much memory your process is using you're probably not getting a very accurate reading.

Have a read of this article: http://www.itwriting.com/dotnetmem.php

It explains some of the shortfalls with using TaskManager as a means to measure the memory usage of your .Net application.

theburningmonk
+1  A: 

My suggestion would be to crank up Windbg and find out what objects exist in memory.
Agreed that we devs generally use it as the last option but in this case, it would give you the exact reason for the memory increase

Bharath K
That or a nice profiler.
ChaosPandion
I ran a profiler and GC runs after 5m30s and 14m14s. The string instances seem to get cleaned up. Task Manager is not trustworthy.
pika81
+3  A: 

You are assuming that the memory usage should not increase. Wrong assumption, that's just not how either the .NET garbage collector or the Windows heap manager work. Both of them work efficiently by using memory that's available for use instead of constantly releasing and reallocating memory.

Let it run for a week. Might go quicker if you make the Interval smaller. Also minimize the form for spectacular effects.

Hans Passant