带计时器的简单应用程序会耗尽内存吗?
谁能解释为什么这个小应用程序的内存使用量不断增加?
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您假设内存使用量不应增加。错误的假设,这不是 .NET 垃圾收集器或 Windows 堆管理器的工作方式。它们都通过使用可用的内存而不是不断释放和重新分配内存来有效地工作。
让它运行一周。如果你把间隔缩小一点,可能会更快。还可以最小化形式以获得壮观的效果。
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.
我的建议是启动 Windbg 并找出内存中存在哪些对象。
同意我们开发人员通常将其用作最后一个选项,但在这种情况下,它会给您内存增加的确切原因
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
我在挖掘
DefaultTraceListener
的源代码时发现了这一点:因此,内存使用量可能增长得太慢,GC 无法立即做出反应。
I was digging through the source of
DefaultTraceListener
and I found this:So the memory usage is probably growing too slowly for the GC to react immediately.
如果您只是查看任务管理器来了解进程使用了多少内存,则可能无法获得非常准确的读数。
读读这篇文章:
http://www.itwriting.com/dotnetmem.php
它解释了一些不足使用 TaskManager 作为测量 .Net 应用程序内存使用情况的方法。
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.