我目前正在編寫一個主要利用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」);'根據需要實現正確的格式化 –
如果讓應用程序運行,或者內存在某個點停止增加,你會崩潰嗎? –