【发布时间】:2013-08-25 18:58:52
【问题描述】:
我目前正在编写一个应用程序,主要使用 DispatcherTimer 来模拟秒表功能。当我的 DispatcherTimer 在应用程序中运行时,我的应用程序的内存使用量在不到 10 分钟内上升到 100MB,考虑到应用程序的功能是多么简单,这尤其奇怪。这通常不会成为问题,除非应用程序的内存使用量迅速增加,然后导致它崩溃并关闭。我浏览了整个网络,并反复遇到承认存在 DispatcherTimer 内存泄漏的文章,但是针对此内存泄漏的所有修复都包括在不再需要 DispatcherTimer 时停止它。我的内存泄漏是在仍然需要 DispatcherTimer 时发生的,而不是在它意外运行时发生的。我需要允许用户让他们的秒表运行他们选择的时间,因此当不再需要 DispatcherTimer 时停止它对我来说没有多大用处。我尝试在 TimerTick 事件处理程序的末尾添加 GC.Collect(),但是,这似乎也没有多大作用。
public MainPage()
{
InitializeComponent();
PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
Timer.Stop();
Timer.Interval = new TimeSpan(0, 0, 1);
Timer.Tick += new EventHandler(TimerTick);
Loaded += new System.Windows.RoutedEventHandler(MainPage_Loaded);
}
void TimerTick(object sender, EventArgs e)
{
timeSpan1 = DateTime.Now.Subtract(StartTimer);
timeSpan2 = DateTime.Now.Subtract(StartTimer2);
WatchHour.Text = timeSpan1.Hours.ToString();
WatchMinute.Text = timeSpan1.Minutes.ToString();
WatchSecond.Text = timeSpan1.Seconds.ToString();
SecondaryHour.Text = timeSpan2.Hours.ToString();
SecondaryMinute.Text = timeSpan2.Minutes.ToString();
SecondarySecond.Text = timeSpan2.Seconds.ToString();
if (WatchHour.Text.Length == 1) WatchHour.Text = "0" + WatchHour.Text;
if (WatchMinute.Text.Length == 1) WatchMinute.Text = "0" + WatchMinute.Text;
if (WatchSecond.Text.Length == 1) WatchSecond.Text = "0" + WatchSecond.Text;
if (SecondaryHour.Text.Length == 1) SecondaryHour.Text = "0" + SecondaryHour.Text;
if (SecondaryMinute.Text.Length == 1) SecondaryMinute.Text = "0" + SecondaryMinute.Text;
if (SecondarySecond.Text.Length == 1) SecondarySecond.Text = "0" + SecondarySecond.Text;
}
这是我的 TimerTick 事件处理程序和一些我的 MainPage 构造函数,事件处理程序中的文本框显示从启动秒表经过的时间。我在这里做错了什么会导致内存如此巨大的增加吗?我以前认为这个问题是因为默认情况下 TextBox 以某种方式缓存了它们以前的内容,再加上由于秒表功能而导致的文本快速变化,但是,在从我的应用程序中完全删除 TextBox 并对其进行分析之后,我很确定它们是不是问题。如上所述,在 TimerTick 处理程序的末尾添加 GC.Collect() 并没有减少我的内存使用量。有没有人知道我可以如何使用 DispatcherTimer 减少内存使用量,也许是通过某种方式操纵 GC 函数来实际工作?
提前致谢!
【问题讨论】:
-
如何在滴答事件开始时停止计时器,并在结束时重新启动?
-
我不认为上面的代码有问题。我怀疑的其他地方的罪魁祸首。顺便说一句,使用
WatchHour.Text = timeSpan1.Hours.ToString("00");来实现您需要的正确格式 -
如果你让它运行,你的应用程序会崩溃,还是内存在某个时候停止增加?
-
内存永远不会停止增加,如果我让它运行足够长的时间,它总是会崩溃
-
@NirKornfeld 我尝试在 Tick 事件中添加停止然后启动计时器,但问题仍然存在
标签: c# memory-leaks windows-phone-8 garbage-collection dispatchertimer