简体   繁体   English

带有计时器的简单应用会消耗掉内存吗?

[英]Simple app with timer is eating memory away?

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 皮卡81

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. 错误的假设是,.NET垃圾收集器或Windows堆管理器都不是这样工作的。 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. 同时最小化形式以获得壮观的效果。

I was digging through the source of DefaultTraceListener and I found this: 我正在挖掘DefaultTraceListener的来源,发现了这一点:

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. 因此,内存使用量可能增长得太慢,以至于GC无法立即做出反应。

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 阅读本文: 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. 它解释了使用TaskManager作为衡量.Net应用程序的内存使用情况的方法的一些不足。

My suggestion would be to crank up Windbg and find out what objects exist in memory. 我的建议是启动Windbg并找出内存中存在哪些对象。
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 同意我们的开发人员通常将其用作最后一个选项,但是在这种情况下,它将为您提供内存增加的确切原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM