我目前正在编写一个主要利用DispatcherTimer来模拟秒表功能的应用程序。当我的DispatcherTimer在应用程序中运行时,我的应用程序的内存使用量在不到10分钟的时间内就会增加到100MB,考虑到应用程序的功能有多简单,这特别奇怪。这通常不会成为问题,除非应用程序的内存使用量迅速增加,然后导致其崩溃并关闭。我查看了整个网络,并且一再发现有文章承认存在DispatcherTimer内存泄漏,但是对此内存泄漏的所有修复包括在不再需要时停止DispatcherTimer。我的内存泄漏发生在DispatcherTimer仍然需要时,而不是在意外运行时。我需要允许用户保持秒表运行,无论他们选择了多长时间,因此在不再需要时停止DispatcherTimer对我来说没有太大帮助。我曾尝试在我的TimerTick事件处理程序的末尾添加GC.Collect(),但是,这似乎也没有做太多。DispatcherTimer不断增加内存使用量,直到应用程序崩溃
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的,存在于事件处理程序的文本框显示从开始秒表经过的时间。我在这里做了一些特别错误的事情,导致内存如此巨大的增加?我以前认为这个问题是因为TextBoxes默认缓存了其以前的内容,加上由于秒表功能导致的文本快速变化,但是,在完全从应用程序中删除TextBox并分析它之后,我确信它们不是这个问题。如上所述,在此TimerTick处理程序的末尾添加GC.Collect()并没有做任何事情来减少我的内存使用量。有没有人有一个想法,我可以通过DispatcherTimer减少我的内存使用量,也许通过某种方式操纵GC功能来实际工作?
在此先感谢!
如何在tick事件开始时停止计时器,并在最后再次启动计时器? –
我不认为上述代码存在问题。我怀疑其他地方的罪魁祸首。顺便说一句,使用'WatchHour.Text = timeSpan1.Hours。ToString(“00”);'根据需要实现正确的格式化 –
如果让应用程序运行,或者内存在某个点停止增加,你会崩溃吗? –