我正在创建 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# 通常,当 GC 希望这样做时,对象会被销毁,没有办法强制它这样做。虽然它很懒,但我不会让你的内存耗尽。因此,您希望销毁的对象还没有准备好被收集。未准备好我的意思是在您的应用程序中,您在某处引用了该对象。其中一些引用作为类中的一个字段在整个过程中都很明显,其他的则更难发现,考虑一下:
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
公开的事件,那么它不会被销毁,除非您在 dispose 方法中删除此处理程序:
void Dispose()
{
llc.SomeEvent -= DoSomething;
}
请注意,IDisposable
接口(interface)是一种模式的一部分,它不像析构函数那样由运行时强制执行。您需要确定调用它的时间和地点。
还要注意闭包,它会捕获您的变量,如果这些变量是实例字段,那么实例也会被捕获。
从长远来看,您需要在 Web 上搜索 C# 中的内存泄漏。考虑到这一点,SO 上有很多问题。祝你好运。
关于c# - 未为 XAML 页面调用析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13946114/