Reputation: 147
I am creating a Windows Phone (8) App. I have 2 XAML pages. 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. I put debug statements in Page 1's and Page 2's destructors, but it appears that they are never being called.
How can I ensure that this problem does not happen?
Upvotes: 4
Views: 2373
Reputation: 12629
I c# in general objects are destroyed when GC wishes to do so there are no ways to forces it to do it. 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:
void Dispose()
{
llc.SomeEvent -= DoSomething;
}
Note that IDisposable
interface is part of a pattern that is not enforced by runtime like destructors. 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#. On SO there is a lot of questions considering this so good luck.
Upvotes: 4