简体   繁体   English

不为XAML页面调用析构函数

[英]Destructor not being called for XAML pages

I am creating a Windows Phone (8) App. 我正在创建一个Windows Phone(8)应用程序。 I have 2 XAML pages. 我有2个XAML页面。 If I manually test the following: 如果我手动测试以下内容:

1. From 1st page, go to 2nd page
2. Press the physical Back button.
3. Go to #1.

Eventually (afte switching back and forth ~15 times), the app runs out of memory and crashes. 最终(来回切换~15次),应用程序耗尽内存并崩溃。 I put debug statements in Page 1's and Page 2's destructors, but it appears that they are never being called. 我将调试语句放在第1页和第2页的析构函数中,但看起来它们从未被调用过。

How can I ensure that this problem does not happen? 如何确保不会发生此问题?

I c# in general objects are destroyed when GC wishes to do so there are no ways to forces it to do it. 当c希望这样做时,一般对象中的c#被破坏,没有办法强迫它去做。 Although it is lazy i would not allow your memory to ran out. 虽然很懒,但我不会让你的记忆耗尽。 So objects you expect to be destroyed are not ready to be collected. 因此,您希望销毁的对象尚未准备好被收集。 By not ready I mean that in your application you somewhere have a reference to this object. 如果没有准备好,我的意思是在您的应用程序中,您在某处可以引用此对象。 Some of those references are obvious as a field in class that lives throughout the process, other are harder to spot consider this: 其中一些引用显然是整个过程中存在的一个类中的一个字段,其他更难以发现这一点:

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(){/*.../*}
}

If ShortLivingClass attaches to event exposed by LongLivingClass then it will not be destroyed unless you remove this handler in dispose method: 如果ShortLivingClass重视通过曝光事件LongLivingClass那么就不会被销毁,除非你删除该处理程序处理方法:

 void Dispose()
 {
     llc.SomeEvent -= DoSomething;
 }

Note that IDisposable interface is part of a pattern that is not enforced by runtime like destructors. 请注意, IDisposable接口是运行时不像析构函数那样强制执行的模式的一部分。 You need to determine place and time to call it. 您需要确定调用它的地点和时间。

Also be aware of closure which will capture your variables and if those variables are instance fields then the instance will also be captured. 还要注意将捕获变量的闭包,如果这些变量是实例字段,那么也将捕获实例。

On the long run you need to search the web for memory leaks in c#. 从长远来看,您需要在Web中搜索c#中的内存泄漏。 On SO there is a lot of questions considering this so good luck. 在SO上有很多问题,考虑到这么好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM