[英]Destructor not being called for XAML pages
我正在創建一個Windows Phone(8)應用程序。 我有2個XAML頁面。 如果我手動測試以下內容:
1. From 1st page, go to 2nd page
2. Press the physical Back button.
3. Go to #1.
最終(來回切換~15次),應用程序耗盡內存並崩潰。 我將調試語句放在第1頁和第2頁的析構函數中,但看起來它們從未被調用過。
如何確保不會發生此問題?
當c希望這樣做時,一般對象中的c#被破壞,沒有辦法強迫它去做。 雖然很懶,但我不會讓你的記憶耗盡。 因此,您希望銷毀的對象尚未准備好被收集。 如果沒有准備好,我的意思是在您的應用程序中,您在某處可以引用此對象。 其中一些引用顯然是整個過程中存在的一個類中的一個字段,其他更難以發現這一點:
class LongLivingClass // say main window or some other
// instance that lives considerably longer then the other
{
public event Action SomeEvent;
}
class ShortLivingClass // class that is created and should be destroyed
// many times throughout life of LongLivingClass
{
ShortLivingClass(LongLivingClass llc)
{
llc.SomeEvent += DoSomething;
}
void DoSomething(){/*.../*}
}
如果ShortLivingClass
重視通過曝光事件LongLivingClass
那么就不會被銷毀,除非你刪除該處理程序處理方法:
void Dispose()
{
llc.SomeEvent -= DoSomething;
}
請注意, IDisposable
接口是運行時不像析構函數那樣強制執行的模式的一部分。 您需要確定調用它的地點和時間。
還要注意將捕獲變量的閉包,如果這些變量是實例字段,那么也將捕獲實例。
從長遠來看,您需要在Web中搜索c#中的內存泄漏。 在SO上有很多問題,考慮到這么好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.